What would happen if I Abandon a thread in User Control in .Net
Lets say I have created a Thread from within a control to monitor for a change in a file, and notify the user when it happens. If the form is closed, and consequently my control is hidden, what would happen to that thread? Would it run forever? Is it somehow tied to the control and get garbage collected with the control? If the control is garbage collected and the thread keeps running wo开发者_StackOverflow社区uld that cause an error in the application?
I ask because I am unsure of what event I would use in UserControl to stop the thread when the control's parent form is closed, or how to signal it to stop. So I was curious what would happen if I did nothing.
It really depends on the type of thread. If its a Background Thread
, it will die as soon as the Main Thread
dies.
If it is not a Background Thread
, it will stay alive. Your UI will be closed, but you will still be able to see you exe
in Task Manager
. You will be able to kill it from there.
You can mark you thread as Background
using its IsBackground
property. You must do it before you start your thread.
Example:
Thread thread = new Thread(DoWork);
thread.IsBackground = true;
thread.Start();
精彩评论