gpt4 book ai didi

c# - 如何取消线程?

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

如果是BackgroundWorkere.Cancel - DoWork - 事件处理程序的属性可以报告取消。

我怎样才能用 Thread 达到同样的目的?对象?

最佳答案

这是一种实现方法的完整示例。

private static bool _runThread;
private static object _runThreadLock = new object();

private static void Main(string[] args)
{
_runThread = true;
Thread t = new Thread(() =>
{
Console.WriteLine("Starting thread...");
bool _localRunThread = true;
while (_localRunThread)
{
Console.WriteLine("Working...");
Thread.Sleep(1000);
lock (_runThreadLock)
{
_localRunThread = _runThread;
}
}
Console.WriteLine("Exiting thread...");
});
t.Start();

// wait for any key press, and then exit the app
Console.ReadKey();

// tell the thread to stop
lock (_runThreadLock)
{
_runThread = false;
}

// wait for the thread to finish
t.Join();

Console.WriteLine("All done.");
}

简而言之;该线程检查一个 bool 标志,并在该标志为 true 时一直运行。与调用 Thread.Abort 相比,我更喜欢这种方法,因为它看起来更好更简洁。

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

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