gpt4 book ai didi

multithreading - C#: how terminate a background thread in dispose() method?

转载 作者:行者123 更新时间:2023-12-03 13:22:04 24 4
gpt4 key购买 nike

我有一个运行线程的程序。线程一直执行处理,并且使用一些同步队列。

类快照如下:

public class MyClass:IDisposable
{
private Thread myThread = new Thread(threadFunc);
private volatile bool runThread = true;

public MyClass()
{
myThread.Start();
}

public Dispose()
{
runThread = false;
}

private void threadFunc()
{
try
{
while(runThread){
queue.Take(); //This method blocks the thread if queue is empty. It uses Monitor class
//do some processing
}
}
catch(Exception e){...}
}
private void otherFunc()
{
queue.enqueue(...);//this method is executed by main thread and uses lock while adding element to the queue.
}
}

当我调用 Dispose()方法时,该线程存在 threadFunc()方法,但是几秒钟后,我从该函数“无法评估表达式...”中得到执行,好像胎面在执行某些工作时已终止。也许它刚刚从 queue.Take()阻止中释放出来,并且没有上下文可以运行。我知道我在想什么...

我该如何解决此类问题并从Dispose方法终止线程。

非常感谢!!!

最佳答案

使用接受TakeCancellationToken重载。您可以使用CancellationTokenSource来获得对 token 的引用,该文件也具有Cancel方法,您可以从Dispose调用该方法来取消阻塞Take方法。您可以阅读更多取消here

关于multithreading - C#: how terminate a background thread in dispose() method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4142870/

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