我想知道在类似情况下处理异常的正确方法
---使用解决方案更新代码---
var wt = new List<PendingSettlement>();
var ot = new List<PendingSettlement>();
var otTask = Task.Run(async () => ot = await LoadOtDataAsync().ConfigureAwait(false));
var wtTask = Task.Run(async () => wt = await LoadWtDataAsync().ConfigureAwait(false));
var tasks = new List<Task>
{
otTask, wtTask
};
try
{
await Task.WhenAll(tasks);
}
catch
{
run.WarningMessage = GetInnermostExceptionMessage(wtTask.Exception) + Environment.NewLine + GetInnermostExceptionMessage(otTask.Exception);
string GetInnermostExceptionMessage(Exception e)
{
if (e == null) return string.Empty;
_logger.LogError(e, e.Message);
while (e.InnerException != null) e = e.InnerException;
return e.Message;
}
}
有没有办法确定哪个内部异常对应于哪个任务?
答案 0 :(得分:1)
存储任务(例如var t1 = Task.Run(...);
)。然后,您可以使用t1.Exception
查询异常。您可以简单地忽略随后从done.Wait();
获得的异常。我会写done.ContinueWith(_ => { }).Wait();
来避免抛出和抓住它。