我是否必须中止System.Threading.Thread?

时间:2016-11-02 09:52:44

标签: c# wpf multithreading

我想知道在完成它之后是否必须停止(UI-)线程(从本机C ++项目调用)。或者我可以放手让ASP.NET为我做这个工作吗?

我这样打电话并创建System.Threading.Thread

Thread viewerThread = new Thread(delegate ()
{
    Window window = new MyCustomWPFWindow();
    window.Show();
    System.Windows.Threading.Dispatcher.Run();
});

this.UIThread = viewerThread;

viewerThread.SetApartmentState(ApartmentState.STA);
viewerThread.Start();

我知道有一个Thread.Abort()方法,但是我真的必须中止它,还是有更好的方法,或者我可以放手让.NET处理它。

1 个答案:

答案 0 :(得分:3)

您应该避免Thread.Abort(),仅在第三方组件阻止线程时使用此选项。即便如此,弄清楚它为什么会挂起。 Thread.Abort() == Evil)您应该始终设计没有Abort()的线程。

如果要停止线程,则应关闭Dispatcher。这是一个如何实现它的示例。

// a field to store the guiDispatcher.
Dispatcher guiDispatcher;

// wait event.
ManualResetEvent dispatcherInitialized = new ManualResetEvent(false);

Thread viewerThread = new Thread(delegate ()
{
    Window window = GetDialog(configuration);
    window.Show();
    // get a/the dispatcher of this thread.
    guiDispatcher = Dispatcher.CurrentDispatcher;

    // dispatcher initialized. Set wait event.
    dispatcherInitialized.Set();

    // run dispatcher.
    System.Windows.Threading.Dispatcher.Run();
});

viewerThread.SetApartmentState(ApartmentState.STA);
viewerThread.Start();
dispatcherInitialized.WaitOne();

// ......

// when you want to terminate the thread, just shutdown the dispatcher.
guiDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
// you might want to wait until the thread is terminated.
viewerThread.Join();

如果调度员自行停止,则线程将被清理。如果调度程序没有停止(这会阻止应用程序终止),您可以添加viewerThread.IsBackground = true;