如何杀死在C#主题? [英] How to Kill Thread in C#?

查看:127
本文介绍了如何杀死在C#主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开类型MyMessageAlert形式的线程。
这种形式是当我称呼它会打开一个弹出窗口。
它有它调用30秒后一种方法CloseWindow()一个计时器

  m_messagAlert =新MyMessageAlert(); 
ParameterizedThreadStart thStart =新ParameterizedThreadStart(m_messagAlert.setMessage);
线程线程=新主题(thStart);
thread.Start(strMessage); //在这一点上,MyMessageAlert形式被打开。



我已经定义类型线程的列表:

 公开名单<螺纹> m_listThread; 



每当我创建一个线程的时候,我把它添加到我的列表:

  m_listThread.Add(螺纹); 

当我关闭应用程序,我想这是开幕式MyMessageAlert的形式,将被关闭立即(不等待30秒)。 !
问题是,我不能让它停止



我试着去在名单使用中止()函数的循环杀吧:

 的foreach(在m_listThread线程线程)
{
如果(thread.IsAlive)
Thread.Abort的();
}



但它并不能帮助。


< DIV CLASS =h2_lin>解决方案

也许你想使用背景 - 线程而不是前景-线程。您的应用程序开始至少一个前台线程(主进程线程)。如果你直接使用线程级(如新的Thread(...))创建新的线程,这将是一个前台线程。



一个AppDomain不能卸载时至少一个前台线程仍在运行。为了避免这种情况,你可以创建一个后台线程。通常,您使用后台线程线程池类,或通过设置 <$ C 。$ C>的IsBackground ,物业直接在线程对象



编辑:在的MSDN


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.

解决方案

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.

这篇关于如何杀死在C#主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆