Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中终止线程?_C#_Multithreading_Kill - Fatal编程技术网

如何在C#中终止线程?

如何在C#中终止线程?,c#,multithreading,kill,C#,Multithreading,Kill,我有一个线程可以打开MyMessageAlert类型的表单。 此表单是一个弹出窗口,在我调用它时打开。 它有一个计时器,在30秒后调用CloseWindow()方法 m_messagAlert = new MyMessageAlert(); ParameterizedThreadStart thStart = new ParameterizedThreadStart(m_messagAlert.setMessage); Thread thread = new Thread(thStart);

我有一个线程可以打开MyMessageAlert类型的表单。 此表单是一个弹出窗口,在我调用它时打开。 它有一个计时器,在30秒后调用CloseWindow()方法

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.
我已经定义了一个线程类型列表:

public List<Thread> m_listThread;
关闭应用程序时,我希望已打开的MyMessageAlert类型的表单立即关闭(无需等待30秒)。 问题是我不能让它停下来

我试图通过使用Abort()函数遍历列表来终止它:

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

但是它没有帮助。

也许你想使用后台线程而不是前台线程。应用程序至少从一个前台线程(主进程线程)开始。如果您直接使用Thread类创建新线程(例如new Thread(…),那么这将是一个前台线程

当至少一个前台线程仍在运行时,不会卸载AppDomain。为了避免这种行为,您可以创建一个后台线程。通常使用ThreadPool类中的后台线程,或者直接在thread对象上设置-Property


编辑:一个简短的解释。

嗨,它正在工作!我们刚刚添加了命令thread.IsBackground=true;
foreach (Thread thread in m_listThread)
 {
      if (thread.IsAlive)
           thread.Abort();
 }