我有一个像这样的取消令牌
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,令牌显示它被设置为已取消。
答案 0 :(得分:16)
这是按预期工作的。如果操作被取消,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();
}