我试图从下面的代码中找出如何报告任务列表抛出的所有异常。
此代码段的基本思想是:用户向处理程序发送请求,处理程序创建消息tasks
并将其发送到将其发送到外部系统的类。我在下面列出了涉及的方法。
我必须关闭某些程序,因为我正在调试异常处理程序,并且任务Exception始终为null,因为Waiting for Activiation
除非我在断点上停留的时间足够长,否则它们的状态似乎一直为空。
// Handle the user request
public async void Handle(WriteScanToSys settings)
{
_successfulScanIds = new List<int>();
// create the messages as tasks
var tasks = _factory.CreateMessage(settings).Select(msg => SendScans(msg));
try
{
// wait for all of them to complete
await Task.WhenAll(tasks); // I had ConfigureAwait(false) here, but took it off
}
catch (Exception)
{
foreach (var task in tasks.Where(t => t.Exception != null))
{
// ELMAH
var errorLog = ErrorLog.GetDefault(null);
errorLog.Log(new Error(task.Exception));
}
}
// save to repository
}
// the task to perform
private async Task<IDictionary<string, object>> SendScans(IDictionary<string, object> data)
{
object sysMsg = null;
var response = await _msgCenter.SendMessage(data);
response.TryGetValue("SystemMessage", out sysMsg);
_successfulScanIds.Add(Convert.ToInt32(data["Id"]));
return response;
}
// the communication with the external system (The message center class)
private async Task<IDictionary<string, object>> SendMessage(IDictionary<string, object> msg)
{
var response = new Dictionary<string, object>();
var response = await _client.sendAsync(
new BodyOfRequest(
// Compose Object
));
if (response.ScreenMessage != "SUCCESSFUL")
throw new CustomException("The transaction for job " + job + " failed with msg: " + body.ScreenMessage);
response.Add("SystemMessage", body.ScreenMessage);
return response;
}
您已经懒惰地进行评估了-Select
每次迭代时,的结果都会创建一组新的任务。您可以通过以下方法解决此问题ToList()
:
var tasks = _factory.CreateMessage(settings)
.Select(msg => SendScans(msg))
.ToList();
这样,您正在等待的任务集将与通过foreach
循环检查的任务集相同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句