gpt4 book ai didi

c# - 确保所有线程退出

转载 作者:太空狗 更新时间:2023-10-29 21:06:35 25 4
gpt4 key购买 nike

在一个 win 表单应用程序中,我有一个线程数组,它们是这样启动的:

bool stop = false;
Thread[] threads = new Thread[10];

for (int i = 0; i < threads.Length; i++)
threads[i] = new Thread(new ThreadStart(Job));

// How to make sure all threads have exited, when the boolean = false

void Job()
{
while (!stop)
// Do something
}

现在,如果用户按下 STOP,stop 的 bool 值将设置为 true,因此线程将陆续退出 Job 方法。如何确保所有线程都已退出?

注意:我的情况需要传统线程,TaskLibrary 不适合我的情况。

最佳答案

使用 Join 方法检查所有线程是否已停止。

 foreach (var t in threads)
{
t.Join();
}

关于c# - 确保所有线程退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287460/

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