有谁知道为什么以下代码没有捕获我的ConnectionException,我花了好几个小时...
public async Task LoadContacts(string filter)
{
// We will send find contacts message to all servers supporting addressbook.
var addressBookServers = _addressBookService.GetAddressBookServerList();
// Create task array here to be able to run each task in parallel manner.
var tasksToProcess = new List<Task<SearchContactsResultDto>>(addressBookServers.Count);
for (int i = 0; i < addressBookServers.Count; i++)
tasksToProcess.Add(_addressBookService.SearchContactsAsync(addressBookServers[i].Id, filterUpCaseNoDiacritics));
while (tasksToProcess.Count > 0)
{
var processedTask = await Task.WhenAny(tasksToProcess);
tasksToProcess.Remove(processedTask);
try
{
var serverResponse = await processedTask.ConfigureAwait(false);
var vmToAdd = serverResponse.SearchedContacts
.Where(sc => !SearchedContacts.Exists(c => c.BabelName == sc.BabelName))
.Select(sc => CreateSearchContactViewModel(serverResponse.ServerId, null, sc.Name, sc.BabelName, sc.ContactId));
SearchedContacts.AddRange(vmToAdd);
}
catch (ErrorMessageException eme) { Log.Warning(s => s.Set($"An {nameof(ErrorMessageException)} of type {eme.ErrorMessage.Cause} threw as a response to {nameof(Core.Json.Messages.MsgFindContacts)}. See exception details for further information.", eme)); }
catch (ConnectionException ce) { Log.Info(s => s.Set($"Connection with server cannot be reached. Message of type {nameof(Core.Json.Messages.MsgFindContacts)} cannot be send", ce)); }
catch (TimeoutException te) { Log.Info(s => s.Set($"Request on a message of type {nameof(Core.Json.Messages.MsgFindContacts)} timeouted. See exception details for further details.", te)); }
catch (Exception) {}
}
IsLoadingContacts = false;
}
当SearchContactsAsync抛出异常时,LoadContacts方法不捕获此异常,并将其作为未处理的AggregateException传播。 我写了一些单元测试,它们都通过了,运行应用程序时会出现问题。 我感谢任何帮助。
SearchContactsAsync implementation:
public async Task<SearchContactsResultDto> SearchContactsAsync(int serverId, string filter)
{
var msgFindContactsRes = await _communicationService.SendFindContactsAsync(serverId, filter)
.ConfigureAwait(false);
return new SearchContactsResultDto()
{
ServerId = serverId,
SearchedContacts = msgFindContactsRes.Contacts,
PageNumber = msgFindContactsRes.PageNumber,
PageSize = msgFindContactsRes.PageSize
};
}
SendFindContacsAsync impl:
public Task<MsgFindContactsRes> SendFindContactsAsync(int serverId, string filter)
{
var serverSender = serverConnectionProvider.ProvideSender(serverId);
var msgFindContacts = messageFactory.CreateMsgFindContacts(filter);
return serverSender.SendAsync<MsgFindContactsRes>(msgFindContacts);
}
SendAsync:
public async Task<TExpectedResponse> SendAsync<TExpectedResponse>(IMessage message)
where TExpectedResponse : class, IMessage
{
if (message == null)
throw new ArgumentNullException($"Argument {nameof(message)} cannot be null.");
var response = await _queue.ProvideAsync(message).ConfigureAwait(false);
if (response is TExpectedResponse)
return response as TExpectedResponse;
else throw new InvalidServerResponseException($"Invalid response to a message of type {message.Header.Type}, expected message type: {typeof(TExpectedResponse).FullName}, received message type: {response.Header.Type}. Server id: {_serverConnection.ServerId}");
}
使用TPL队列和TCS提供Async:
public Task<TItemResult> ProvideAsync(TItemData item)
{
TaskCompletionSource<TItemResult> tcs = new TaskCompletionSource<TItemResult>();
// async enqueue an item with its task completion source
_queue.SendAsync<QueueItem<TItemData, TItemResult>>(new QueueItem<TItemData, TItemResult>(tcs, item));
return tcs.Task;
}
最后使用TaskCompletionSource抛出异常的队列使用者:
private async Task StartConsumer(Func<TItemData, TItemResult> consumer)
{
while (await _queue.OutputAvailableAsync())
{
QueueItem<TItemData, TItemResult> res = await _queue.ReceiveAsync();
try
{
var result = consumer(res.Data);
res.Tcs?.SetResult(result);
}
catch (Exception e)
{
res?.Tcs.SetException(e);
throw;
}
}
}
答案 0 :(得分:1)
SearchContactsAsync的任务在这里
for (int i = 0; i < addressBookServers.Count; i++)
tasksToProcess.Add(_addressBookService.SearchContactsAsync(addressBookServers[i].Id, filterUpCaseNoDiacritics));
在try块之外等待那些任务:
var processedTask = await Task.WhenAny(tasksToProcess);
tasksToProcess.Remove(processedTask);
try
{
// Rest of your code
因此,如果其中一个任务抛出异常,则无需处理任何异常。移动线
var processedTask = await Task.WhenAny(tasksToProcess);
tasksToProcess.Remove(processedTask);
在try块内。
答案 1 :(得分:0)
您没有抓住aggregate exception,这就是您的异常无法处理的原因。
//Following code is just an outline and you need to correct according to your requirement.
try {
//your task
}
catch (AggregateException ae)
{
ae.Handle( x =>
{
// Handle an ErrorMessageException
if (x is ErrorMessageException) {
//do your logging
return true; //if you handled it through logging or reporting
}
// Handle an ConnectionException
else if(x is ConnectionException){
//do your logging for connection
return true; //if you handled it through logging or reporting
}
else
return false; //This leave the exception as unhandled aggregate exception.
});
}
答案 2 :(得分:-1)
哦,我现在可以看到问题了。我发布的代码的最后一行......它再次引发异常,这是永远不会被抓住的...这是一个多么糟糕的错误。无论如何,谢谢所有人参与帮助......