我有一个程序运行一个线程。线程一直执行处理,并使用一些同步队列。c#:如何在dispose()方法中终止后台线程?
类快照如下:
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()
方法,但秒钟后我得到一个execption从这个FUNC“无法avaluate表达......” ,就好像在做一些工作时胎面被终止一样。也许它刚刚从queue.Take()
发布,并且没有上下文运行。我知道我错过了一些东西......
我该如何解决这样的问题并从Dispose方法中终止线程。
非常感谢!