我有一些长时间运行的代码,我想作为Task
运行并在需要时使用CancellationTokenSource
取消,但是取消似乎不起作用,因为当调用tokenSource.Cancel()
时我的任务一直在运行(不会引发异常)。
可能缺少明显的东西?
以下剪切示例:
bool init = false;
private void Button1_Click(object sender, EventArgs e)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task task = new Task(() =>
{
while (true)
{
token.ThrowIfCancellationRequested();
if (token.IsCancellationRequested)
{
Console.WriteLine("Operation is going to be cancelled");
throw new Exception("Task cancelled");
}
else
{
// do some work
}
}
}, token);
if (init)
{
tokenSource.Cancel();
button1.Text = "Start again";
init = false;
} else
{
try
{
task.Start();
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
button1.Text = "Cancel";
init = true;
}
}
tokenSource
。第二次Button1_Click
调用取消的令牌与您在第一次调用时传递给任务的令牌不同。第二个问题是您一次又一次地创建新任务,但是您的逻辑建议您希望一个任务应该在第一次单击时创建,并在第二次单击时终止。