Reputation: 4530
I am sometimes getting a cross thread exception when closing my application which uses two threads (main thread and secondary). I think what is happening is that the main UI thread is being disposed while the secondary one is still running, and since the secondary one sometimes invokes things on the UI thread it is crashing.
Do I need to manually close the secondary thread in the FormClosing
event?
Thanks for the info.
Upvotes: 0
Views: 154
Reputation: 10476
The recommended approach in multi-threaded windows application is using Method Invocation
instead of directly manipulating controls which were created on another thread. This way you never get Cross Thread Exception
. For example you can set a textbox's text like this:
form1.BeginInvoke(new MethodInvoker(()=>textbox1.text = "Hello!"));
For more information see: http://msdn.microsoft.com/en-us/library/ms171728(v=vs.85).aspx
Upvotes: 1
Reputation: 7612
Do I need to manually close the secondary thread?
No and yes.
No, if your secondary thread is a background thread. You can inspect/set the IsBackground property on your secondary thread. All background threads are are automatically stopped by CLR when there is no foreground thread running anymore. All ThreadPool threads, for example, are background threads.
Yes, however, is when you perform some critical task in your secondary thread and you don't want it to be abruptly stopped. In that case, you will have to implement appropriate logic to stop your secondary thread.
Upvotes: 1
Reputation: 5369
Once you have a long-running dedicated thread, you have to implement shutdown logic for it. Reason is simple: the app is not killed by OS until at least one thread alive. And yes, there is no such thing as "main thread", all threads are equal from OS perspective.
Given that, once your app plans to exit, you must
Now you're free to exit.
Upvotes: 1