我在WPF应用程序中有这个代码:
this.Closing += WindowOnClosing;
CancellationTokenSource cts = new CancellationTokenSource();
private void func()
{
Task task = new Task.Factory.Start(() =>
{
// long running code...
}), cts.Token);
await task;
}
private void WindowOnClosing(CancelEventArgs e)
{
cts.Cancel();
}
但是当我关闭窗口时,任务仍处于运行状态。
答案 0 :(得分:2)
首先,在这种情况下你不应该使用StartNew
;请改用Task.Run
。正如我在我的博客上解释的那样,StartNew
is dangerous。 (我假设您的实际代码使用StartNew
,因为new Task.Factory.Start
没有任何意义。)
具体来说,CancellationToken
仅取消委托的日程安排;它不会取消代表本身。您必须在自己的代码中回复取消:
private void func()
{
var token = cts.Token;
Task task = Task.Run(() =>
{
...
token.ThrowIfCancellationRequested(); // Occasionally do this.
...
});
await task;
}
答案 1 :(得分:-1)
我认为在取消任务后你应该等待取消:
task.Wait();
这里也很有用:
https://msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx