【发布时间】:2020-03-30 05:53:25
【问题描述】:
我有一些长时间运行的代码,我想以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;
}
}
【问题讨论】:
-
您正在为每个
Button1_Click创建一个新的Task。尝试将task和tokenSource变量移到外部作用域,并初始化一次。 -
@TheodorZoulias 好点,虽然当我将
Task task移出按钮单击处理程序时行为没有改变。仍然没有看到任何异常抛出。 -
您还必须移动令牌源
-
@pinkfloydx33 是的,成功了(根据下面接受的答案)。谢谢。
标签: c# .net winforms task-parallel-library