Peter Peter - 1 month ago 9
C# Question

Do I have to abort a System.Threading.Thread?

I wonder if I have to stop a (UI-)Thread (called from a native C++ Project) after I am finished with it. Or can I just let it go so as ASP.NET does this job for me?

I call and create the

System.Threading.Thread
like this.

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

this.UIThread = viewerThread;

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


I know there is a
Thread.Abort()
Method, but do I really have to abort it or is there a better method or can I just let it go and let .NET handle this.

EDIT:

Changed
WPF
example
Window
initialization and added the tag.

Answer

You should avoid Thread.Abort(), use this only when a third-party component blocks a thread. Even then, figure out why it hangs. (Thread.Abort() == Evil) You should always design your threading without Abort().


You should shutdown the Dispatcher if you want to stop thread. Here's an example on how you could implement it.

// 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();

If the dispatcher stops by it self, the thread will be cleanup. If the dispatcher doesn't stop (which prevents the application from terminating), you can add viewerThread.IsBackground = true;

Comments