用.net任务并行库捕获错误
本文关键字:错误 并行 net 任务 | 更新日期: 2023-09-27 18:12:50
这是我尝试捕获错误的两个替代方案,它们似乎都做同样的事情。但是哪一种比另一种更可取呢?为什么呢?
Alt 1:
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
try
{
Task t = Task.Run(() =>
{
_someObj.SomeMethod();
});
await t; //wait here, without blocking...
}
catch (Exception ex)
{
string errMsg = ex.Message + Environment.NewLine;
errMsg += "some unhandled error occurred in SomeMethod";
Log(errMsg);
return; //<-- bypass below code on error...
}
//other code below... does not execute...
DoSomethingElse();
}
Alt 2:
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
bool errOccurred = false;
Task t = Task.Run(() =>
{
try
{
_someObj.SomeMethod();
}
catch (Exception ex)
{
string errMsg = ex.Message + Environment.NewLine;
errMsg += "some unhandled error occurred in SomeMethod";
Log(errMsg);
errOccurred = true;
}//end-Catch
});
await t; //wait here, without blocking...
if (errOccurred) return; //<-- bypass below code on error...
//other code below... does not execute...
DoSomethingElse();
}
更好的选择是将部分代码重构成一个单独的方法,返回一个bool值,指示是否继续。
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
bool success = await SomeMethodAsync();
if (!success)
{
return;
}
//other code below... does not execute...
DoSomethingElse();
}
private async Task<bool> SomeMethodAsync()
{
try
{
await Task.Run(() => _someObj.SomeMethod());
return true;
}
catch (Exception ex)
{
string errMsg = string.Format("{0} {1}some unhandled error occurred in SomeMethod",
ex.Message, Environment.NewLine);
Log(errMsg);
return false;
}
}
最好是重构代码,而不是把它们都放在同一个地方。如果你需要做的只是记录它,那么最好在委托中捕获异常。
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
try
{
DoSomeWork();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
}
然而,如果您有另一个方法DoSomethingElse()
,可能会受到任务结果的影响。try catch
最好包裹在await
周围
private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
try
{
await Task.Run(() =>
{
try
{
DoSomeWork();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
});
DoSomethingElse();
}
catch(Exception ex)
{
}
}
这要看情况而定。
我想说重构Task. run()部分为一个单独的异步任务方法,就像Sriram Sakthivel的回答一样,通常是一件好事。它避免了像版本2中那样在lambda中使用捕获的bool,并且它允许您编写更简洁地表达意图的代码。
也就是说,我会仔细考虑"catch all -> log -> ignore"模式是否是您想要的。一般来说:捕获特定的异常并专门处理它们。对于所有其他异常,您可以记录它们,但仍然用"throw;"或"throw new MoreSpecificException(originalException);"重新抛出它们。
考虑到这一点,我建议如果您使用捕获全部方法,您应该像版本1中那样执行捕获全部方法。
为了保持高可读性,使代码简洁,意图明确,并明确处理异常,我会这样写:
private async void BtnClick(object sender, RoutedEventArgs e)
{
try
{
if (await TryDoSomethingAsync())
{
DoSomeMoreStuff();
}
}
catch (Exception ex)
{
// I am sure it is fine that any and all exceptions can be logged and ignored.
Log(ex);
// And maybe even notify the user, since I mean, who monitors log files anyway?
// If something that shouldn't go wrong goes wrong, it's nice to know about it.
BlowUpInYourFace(ex);
}
}
private async Task<bool> TryDoSomethingAsync()
{
return await Task.Run<bool>(() =>
{
try
{
_myService.DoSomething();
}
catch (SomeKnownException ske)
{
// An expected exception which is fine to ignore and return unsuccessful.
Log(ske);
return false;
}
catch (SomeOtherKnownException soke)
{
// Expected exception that indicates something less trivial, but could be more precise.
throw new MyMorePreciseException(soke);
}
// Nothing went wrong, so ok.
return true;
});
}