【发布时间】:2022-02-23 03:47:48
【问题描述】:
我正在使用这些 Windows 8 WinRT 任务,并且我正在尝试使用以下方法取消任务,并且它在某些时候有效。确实调用了 CancelNotification 方法,这让您认为任务已取消,但在后台任务继续运行,然后在完成后,任务的状态始终为完成且从未取消。有没有办法在任务被取消时完全停止它?
private async void TryTask()
{
CancellationTokenSource source = new CancellationTokenSource();
source.Token.Register(CancelNotification);
source.CancelAfter(TimeSpan.FromSeconds(1));
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token);
await task;
if (task.IsCompleted)
{
MessageDialog md = new MessageDialog(task.Result.ToString());
await md.ShowAsync();
}
else
{
MessageDialog md = new MessageDialog("Uncompleted");
await md.ShowAsync();
}
}
private int slowFunc(int a, int b)
{
string someString = string.Empty;
for (int i = 0; i < 200000; i++)
{
someString += "a";
}
return a + b;
}
private void CancelNotification()
{
}
【问题讨论】:
-
刚刚找到this article,它帮助我了解了各种取消方式。
标签: c# task-parallel-library .net-4.5