首页 > 解决方案 > 如何正确取消 C# 中的任务?

问题描述

CancellationTokenSource似乎忽略了循环操作的时间。迭代它需要一段时间,我将限制设置为 500 毫秒,但它忽略了它。我可能做错了什么?

static async Task<int> Thread1()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromMilliseconds(500));
  return await Task.Run(async () =>
  {
    using (var client = new HttpClient())
    {          
      var site = await client.GetAsync("http://webcode.me", source.Token);
      for (int i = 0; i < 10000000; i++)
      {
        Console.WriteLine(i);
      }
      string content = await site.Content.ReadAsStringAsync();
      return content.Count(x => x == 'e');
    }
  }, source.Token);
}

标签: c#multithreading

解决方案


您永远不会在循环中检查取消。

在循环中调用以下内容:

https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.throwifcancellationrequested?view=netframework-4.8

例如

token.ThrowIfCancellationRequested(); 

这等于:

if (token.IsCancellationRequested)   
    throw new OperationCanceledException(token);  

推荐阅读