c# - CancellationToken 甚至为空
问题描述
在我的应用程序中,我运行 aTask
执行繁重的操作,我试图停止执行该Task
. 实际上,我在课堂上声明了以下结构:
public class Foo
{
private CancellationTokenSource tokenSource = new CancellationTokenSource();
private CancellationToken token;
public void Start()
{
var task = new Task(async () => {
try
{
await new Bot().StartAsync(token);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}, token));
task.Start();
}
}
如您所见,我已经声明了一个CancellationTokenSource
允许我在用户单击按钮时停止任务执行:
StopTask_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
}
现在,在该StartAsync
方法中,我有以下代码:
public async Task StartAsync(CancellationToken token)
{
ApplicationToken = token;
while(true)
{
if(ApplicationToken.IsCancellationRequested)
{
break;
}
}
}
将ApplicationToken
作为参数传递的令牌存储在StartAsync
方法类中。
在按钮单击事件之后,请求应该被取消但没有任何反应。
然后我检查每次迭代是否有取消请求,但变量值为 even false
。
解决方案
嗯,看来你忘了token = tokenSource.Token;
Edit1:您应该使用检查取消ThrowIfCancellationRequested()
编辑2:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace CancellationTokenPOC
{
class Program
{
public static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
TokenPOC t = new TokenPOC();
var longRunningTask = Task.Factory.StartNew(async () =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
t.token.ThrowIfCancellationRequested();
await Task.Delay(10000);
}
});
Console.ReadKey();
t.source.Cancel();
await Task.Delay(1000);
Console.WriteLine("finishing");
}
}
class TokenPOC
{
public CancellationTokenSource source = new CancellationTokenSource();
public CancellationToken token;
public TokenPOC()
{
token = source.Token;
}
}
}
该令牌被取消并按预期结束程序......
推荐阅读
- python - 在 MMS 中将请求作为媒体发布
- object-detection-api - 使用 tensorflow 对象检测 api 训练 CenterNet MobileNetV2 FPN 512x512 时出现错误“indices[0] = 0 not in [0,0)”
- java - Java流,从对象中获取多个属性
- python - Ubuntu Apache 上的 Flask / 错误 404 在此服务器上找不到请求的 URL
- sql - SQL:使用多个 CASE 语句优化查询
- microservices - 在 POST 方法中使用 MicroserviceResponse 作为请求体
- python - 将同一列中的多个非日期格式转换为适当的 pandas datetime 对象
- excel - Excel VBA条件格式 - 计算范围的行数
- java - 在 Java 流中使用基于过滤器的不同映射逻辑
- javascript - VueJS 中的作用域插槽到底是什么?