尝试捕捉外:等待Task.Run(() [英] Try Catch outside of: await Task.Run(()
问题描述
是否尝试外陷阱:等待Task.Run(()=>
有意义或只是使用它们只在计谋的
专用异步无效测试()
{
尝试
{
等待Task.Run(()=>
{
尝试
{
DoingSomething();
}
赶上(例外前)
{
log.Error(ex.Message);
}
});
}
赶上(例外前)
{
log.Error(ex.Message);
}
}
如果您处理异常
委托(在你的情况只是为了记录的目的)内,等待
不会提高在正常情况下例外。这应该是好的。
专用异步任务测试()
{
等待Task.Run(()=>
{
尝试
{
DoingSomething();
}
赶上(例外前)
{
log.Error(ex.Message);
}
});
}
不过,既然你是等待
荷兰国际集团的工作
,最有可能,会有一些 DoSomethingElse
在测试
的方法,这可能会影响结果的工作
- 在这种情况下,它也是情理之中有一个的try / catch
围绕等待
专用异步任务测试()
{
尝试
{
等待Task.Run(()=>
{
尝试
{
DoingSomething();
}
赶上(SomeSpecialException SPEX)
{
//它是确定有此异常
log.Error(ex.Message);
}
});
DoSomethingElse(); //当意外发生异常时不运行。
}
赶上(例外前)
{
//这里我们也捕获的SynchronizationContext运行
//所以,可以更新用户界面显示的错误....
}
}
Does try catch outside of: await Task.Run(() =>
make sense or just use them only inside of await?
private async void Test()
{
try
{
await Task.Run(() =>
{
try
{
DoingSomething();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
If you handle Exception
inside the delegate (in your case just for logging purpose), await
will not raise an exception in normal circumstances. This should be fine.
private async Task Test()
{
await Task.Run(() =>
{
try
{
DoingSomething();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
}
However, since you are await
ing the Task
, most probably, there will be some DoSomethingElse
in the Test
method, which might be affected by the outcome of the Task
- in which case it also makes sense to have a try/catch
around await
.
private async Task Test()
{
try
{
await Task.Run(() =>
{
try
{
DoingSomething();
}
catch (SomeSpecialException spex)
{
// it is OK to have this exception
log.Error(ex.Message);
}
});
DoSomethingElse(); // does not run when unexpected exception occurs.
}
catch (Exception ex)
{
// Here we are also running on captured SynchronizationContext
// So, can update UI to show error ....
}
}
这篇关于尝试捕捉外:等待Task.Run(()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!