How to Kill Thread in C#?

风流意气都作罢 提交于 2019-12-19 10:12:25

问题


I have a thread that opens a form of type MyMessageAlert. This form is a popup window that is opened when I call it. It has a timer which calls a method CloseWindow() after 30 seconds.

m_messagAlert = new MyMessageAlert(); 
ParameterizedThreadStart thStart = new ParameterizedThreadStart(m_messagAlert.setMessage);
Thread thread = new Thread(thStart);
thread.Start(strMessage); //at this point, the MyMessageAlert form is opened.

I have defined a list of type thread:

public List<Thread> m_listThread;

Each time that I create a thread, I add it to my list:

m_listThread.Add(thread);

When I close the application, I want that the form of type MyMessageAlert that was opened, will be closed immediately (without waiting 30 seconds). Problem is that I can't make it stop!

I tried to kill it by going over the list with a loop using the Abort() function:

foreach (Thread thread in m_listThread)
 {
      if (thread.IsAlive)
           thread.Abort();
 }

But it doesn't help.


回答1:


Maybe you want to use Background-Threads instead of Foreground-Threads. Your application start with at least one Foreground-Thread (main process thread). If you create new Threads using the Thread-class directly (e. g. new Thread(...)), this will be an foreground thread.

An AppDomain is not unloaded when at least one foreground thread is still running. To avoid this behavior you can create a background thread. Typically you use background threads from the ThreadPool-class, or by setting the IsBackground-Property at the thread object directly.

edit: An short explanation at the MSDN.



来源:https://stackoverflow.com/questions/4779791/how-to-kill-thread-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!