我正在处理这些 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()
{
}
继续阅读消除 https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads(在 .NET 4.0 中引入,此后基本没有变化)和基于任务的异步模式 https://web.archive.org/web/20150406071541/http://www.microsoft.com/en-us/download/details.aspx?id=19957,它提供了如何使用的指南CancellationToken
with async
方法。
总而言之,您通过CancellationToken
到每个支持取消的方法中,并且该方法必须定期检查它。
private async Task TryTask()
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(1));
Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);
// (A canceled task will raise an exception when awaited).
await task;
}
private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
string someString = string.Empty;
for (int i = 0; i < 200000; i++)
{
someString += "a";
if (i % 1000 == 0)
cancellationToken.ThrowIfCancellationRequested();
}
return a + b;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)