15

我有一个像这样的取消令牌

   static CancellationTokenSource TokenSource= new CancellationTokenSource();

我有一个像这样的阻塞集合

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

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

if(TokenSource.CancelPending)
   return;

当我打电话

TokenSource.Cancel();

Take 不会像它应该的那样继续。如果我将 TryTake 与投票一起使用,则令牌显示它被设置为已取消。

4

1 回答 1

18

这按预期工作。如果操作被取消,items.Take会抛出OperationCanceledException. 这段代码说明了它:

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();
}
于 2011-04-22T20:45:05.377 回答