我有以下示例代码:
static class Program
{
static void Main()
{
var cts = new CancellationTokenSource();
var task = Task.Factory.StartNew(
() =>
{
try
{
Console.WriteLine("Task: Running");
Thread.Sleep(5000);
Console.WriteLine("Task: ThrowIfCancellationRequested");
cts.Token.ThrowIfCancellationRequested();
Thread.Sleep(2000);
Console.WriteLine("Task: Completed");
}
catch (Exception exception)
{
Console.WriteLine("Task: " + exception.GetType().Name);
throw;
}
}).ContinueWith(t => Console.WriteLine("ContinueWith: cts.IsCancellationRequested = {0}, task.IsCanceled = {1}, task.Exception = {2}", cts.IsCancellationRequested, t.IsCanceled, t.Exception == null ? "null" : t.Exception.GetType().Name));
Thread.Sleep(1000);
Console.WriteLine("Main: Cancel");
cts.Cancel();
try
{
Console.WriteLine("Main: Wait");
task.Wait();
}
catch (Exception exception)
{
Console.WriteLine("Main: Catch " + exception.GetType().Name);
}
Console.WriteLine("Main: task.IsCanceled = {0}", task.IsCanceled);
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
输出是:
- 任务:跑步
- 主要:取消
- 主要:等等
- 任务:ThrowIfCancellationRequested
- 任务:操作取消异常
- 继续:cts.IsCancellationRequested = True,task.IsCanceled = False,task.Exception = AggregateException
- 主要:task.IsCanceled = False
- 按任何一个键退出...
如果我删除ContinueWith,则输出为:
- 任务:跑步
- 主要:取消
- 主要:等等
- 任务:ThrowIfCancellationRequested
- 任务:操作取消异常
- 主要:捕获聚合异常
- 主要:task.IsCanceled = False
- 按任何一个键退出...
我不明白,为什么 task.IsCanceled 在这两种情况下都返回 false?
为什么只在没有ContinueWith的情况下重新抛出异常?
我想要实现的是一种等待任务完成的统一且简单的方法,以及一个指示任务是否被取消的属性。
我认为你并没有取消任务本身,而只是抛出任务异常。尝试使用StartNew http://msdn.microsoft.com/en-us/library/dd988458.aspx(Action操作,CancellationToken取消令牌)而不是StartNew(Action操作)。您还可以将取消令牌作为参数添加到ContinueWith。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)