2011-04-22 4 views
12

나는CancellationToken BlockingCollection에서 벗어나지 않는 취소

 static CancellationTokenSource TokenSource= new CancellationTokenSource(); 
 static CancellationTokenSource TokenSource= new CancellationTokenSource(); 

BlockingCollection<object> items= new BlockingCollection<object>(); 

var item = items.Take(TokenSource.Token); 

if(TokenSource.CancelPending) 
    return; 

TokenSource.Cancel(); 

을 호출 할 때 걸리는 작업을 계속하지 않아도됩니다. 설문 조사와 함께 TryTake를 사용하면 토큰에 취소 된 것으로 표시됩니다.

답변

15

예상대로 작동합니다. 작업이 취소되면 items.TakeOperationCanceledException을 반환합니다. 이 코드는 다음과 같습니다.

static void DoIt() 
{ 
    BlockingCollection<int> items = new BlockingCollection<int>(); 
    CancellationTokenSource src = new CancellationTokenSource(); 
    ThreadPool.QueueUserWorkItem((s) => 
     { 
      Console.WriteLine("Thread started. Waiting for item or cancel."); 
      try 
      { 
       var x = items.Take(src.Token); 
       Console.WriteLine("Take operation successful."); 
      } 
      catch (OperationCanceledException) 
      { 
       Console.WriteLine("Take operation was canceled. IsCancellationRequested={0}", src.IsCancellationRequested); 
      } 
     }); 
    Console.WriteLine("Press ENTER to cancel wait."); 
    Console.ReadLine(); 
    src.Cancel(false); 
    Console.WriteLine("Cancel sent. Press Enter when done."); 
    Console.ReadLine(); 
} 
관련 문제