C#中如何杀死线程?

发布于 2024-10-13 06:30:05 字数 790 浏览 5 评论 0原文

我有一个线程打开 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;

每次创建线程时,我都会将其添加到我的列表中:

m_listThread.Add(thread);

当我关闭应用程序时,我希望打开的 MyMessageAlert 类型的表单将立即关闭(无需等待 30秒)。 问题是我无法阻止它!

我试图通过使用 Abort() 函数循环遍历列表来杀死它:

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

但这没有帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-10-20 06:30:05

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

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

编辑:MSDN 上的简短说明。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文