Ily*_*yas 0 c# task-parallel-library
嗨,我有以下代码:
try
{
var t1 = Task.Factory.StartNew(() =>
{
Count(5, 10);
});
//t1.Wait(); //This line if uncommented causes the exception to be handled below....
Console.WriteLine("done");
}
catch (AggregateException ex)
{
Console.WriteLine(ex);
}
private void Count(int start, int end)
{
for (var i = start; i <= end; i++)
{
Console.WriteLine(i);
if (i == 7) throw new InvalidOperationException("Something bad happened");
Thread.Sleep(1000);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我不想等待我的任务,但仍想处理异常,我该如何实现?
创建一个在任务失败时处理错误的延续:
var t1 = Task.Factory.StartNew(() =>
{
Count(5, 10);
});
t1.ContinueWith(
(task) =>
{
var error = task.Exception;
// handle error
}, TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)
OnlyOnFaulted
指定如果任务失败,则继续将在线程池线程上运行.如果任务成功完成,则不会执行.
归档时间: |
|
查看次数: |
608 次 |
最近记录: |