Rys*_*gan 2 c# task task-parallel-library
我有以下示例代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
如果我删除ContinueWith,则输出为:
我不明白,为什么task.IsCanceled在两种情况下都返回false?
为什么只有没有ContinueWith才能重新抛出异常?
我想要实现的是一种等待任务完成的统一和简单的方法,以及一个指示任务是否被取消的属性.
| 归档时间: |
|
| 查看次数: |
1452 次 |
| 最近记录: |