c# - 如何正确取消 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);
}
解决方案
您永远不会在循环中检查取消。
在循环中调用以下内容:
例如
token.ThrowIfCancellationRequested();
这等于:
if (token.IsCancellationRequested)
throw new OperationCanceledException(token);
推荐阅读
- python-3.x - 如何根据另一列计算数据框中的常见元素
- javascript - php 没有收到来自 ajax 类型帖子的任何请求,是否需要在邮件中提及用户名和密码
- ios - 我正在使用 Xcode10.1,但它意外崩溃
- flutter - 为什么可拖动的容器在拖动时没有圆角?
- javascript - 过滤其中包含另一个数组的数组
- reactjs - 如何用lunr js和reactjs创建索引?
- python - 由标记定义的区域的平均颜色
- three.js - 如何导出适用于 Andorid 场景查看器的 gltf?
- javascript - Vue.js 中的 googleapis:TypeError:“原始”参数必须是函数类型
- failed-installation - ESP8266 板停止通过板管理器安装