2010-11-10 122 views
1

我有一個程序運行一個線程。線程一直執行處理,並使用一些同步隊列。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方法中終止線程。

非常感謝!

回答

2

使用的Take接受一個CancellationToken過載。您可以通過使用CancellationTokenSource獲得對令牌的引用,其中CancellationTokenSource也有Cancel方法,您可以從Dispose調用該方法以取消阻止Take方法。你可以閱讀更多取消here