在 await Task.Run(() =>
之外的 try catch 是否有意义,或者仅在 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);
}
}
最佳答案
如果你处理 Exception
在委托(delegate)内部(在您的情况下仅用于记录目的),await
在正常情况下不会引发异常。这应该没问题。
private async Task Test()
{
await Task.Run(() =>
{
try
{
DoingSomething();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
}
但是,既然你是await
正在 Task
, 很可能会有一些 DoSomethingElse
在Test
方法,这可能会受到 Task
的结果的影响- 在这种情况下,拥有一个 try/catch
也是有意义的周围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 ....
}
}
关于c# - 尝试在 : await Task. 之外捕获 Run((),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704102/