我正在按照此处的示例代码来了解异步任务。我修改了代码以编写任务工作与主要工作的一些输出。输出将如下所示:
我注意到,如果我删除 Wait() 调用,程序运行相同,除了我无法捕获任务取消时引发的异常。有人可以解释需要 Wait() 才能击中 catch 块的幕后发生的事情吗?
一个警告是,Visual Studio 调试器将错误地停止在Console.WriteLine(" - task work");
消息“OperationCanceledException 未被用户代码处理”的行上。发生这种情况时,只需单击继续或按 F5 即可查看程序的其余部分运行。有关详细信息,请参阅http://blogs.msdn.com/b/pfxteam/archive/2010/01/11/9946736.aspx。
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
class Program
{
static void Main()
{
var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;
// Delegate representing work that the task will do.
var workDelegate
= (Action)
(
() =>
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
// "If task has been cancelled, throw exception to return"
// Simulate task work
Console.WriteLine(" - task work"); //Visual Studio
//erroneously stops on exception here. Just continue (F5).
//See http://blogs.msdn.com/b/pfxteam/archive/2010/01/11/9946736.aspx
Thread.Sleep(100);
}
}
);
try
{
// Start the task
var task = Task.Factory.StartNew(workDelegate, cancellationToken);
// Simulate main work
for (var i = 0; i < 5; i++)
{
Console.WriteLine("main work");
Thread.Sleep(200);
}
// Cancel the task
tokenSource.Cancel();
// Why is this Wait() necessary to catch the exception?
// If I reomve it, the catch (below) is never hit,
//but the program runs as before.
task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine(e.Message);
foreach (var innerException in e.InnerExceptions)
Console.WriteLine(innerException.Message);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}