gpt4 book ai didi

c# - 如何中止多个线程?

转载 作者:太空狗 更新时间:2023-10-29 22:34:42 25 4
gpt4 key购买 nike

在这段代码中,当 button1 被点击两次时,它创建了 2 个独立的线程。单击一次,它会在堆上创建一个新线程,字段 t1 指向堆上的新线程。当我单击 button2 时,它会中止最后一个线程(t1 指的是)。

如何中止其他线程?

Thread t1;
ThreadStart ts1;

private void button1_Click(object sender, EventArgs e)
{
ts1 = new ThreadStart(myfunc);
t1 = new Thread(ts1);
t1.Start();
}

private void button2_Click(object sender, EventArgs e)
{
t1.Abort();
}

最佳答案

好吧,面向对象的答案是将线程列表保存为一个字段。

private readonly List<Thread> threads = new List<Thread>();

然后将新构造的线程添加到第一个处理程序的列表中。

var thread = new Thread(myfunc);
thread.Start();
threads.Add(thread);

然后您可以遍历第二个处理程序中的每个线程,依次中止每个线程。

foreach(var thread in threads)
thread.Abort();

但我认为这里最重要的一点是,几乎从来没有调用 Thread.Abort 的充分理由。

来自MSDN page :

When a thread calls Abort on itself, the effect is similar to throwing an exception; the ThreadAbortException happens immediately, and the result is predictable. However, if one thread calls Abort on another thread, the abort interrupts whatever code is running. There is also a chance that a static constructor could be aborted. In rare cases, this might prevent instances of that class from being created in that application domain. In the .NET Framework versions 1.0 and 1.1, there is a chance the thread could abort while a finally block is running, in which case the finally block is aborted.

The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.

最好使用某种形式的信号,例如设置一个 ManualResetEvent,每个线程将以周期性的时间间隔进行轮询。或者,您可以使用支持任务取消的 BackgroundWorker 类(对其调用 CancelAsync,并让工作线程测试 CancellationPending 定期)。如果您使用的是 .NET 4.0,您还可以使用 TPL .

关于c# - 如何中止多个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4183423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com