[英]async Exception not being caught
我有一个Windows服务,引用以下代码。 我的使用以下方法的代码包含一个try..catch
块,但似乎没有catch
在以下方法中thrown
RefereshTokenException
。 显然,我对async
理解是不正确的。
private async void RefreshTokens()
{
try
{
var cognito = new CognitoApi();
var response = cognito.TokenRefresh(_refreshToken);
if (response.HttpStatusCode == HttpStatusCode.OK)
{
_idToken = new AwsToken(response.AuthenticationResult.IdToken);
_accessToken = new AwsToken(response.AuthenticationResult.AccessToken);
}
else
{
await _signIn(_credentials.SiteId, _credentials.LocationId, null);
}
}
catch (NotAuthorizedException)
{
await _signIn(_credentials.SiteId, _credentials.LocationId, null);
}
catch (Exception ex)
{
throw new RefreshTokenException("Failed refreshing tokens.", ex);
}
}
这是调用RefreshTokens
的代码
public async void Process(QueueMessage queueMessage, Action<QueueMessage> retryAction)
{
_processingCounter.Increment();
try
{
......
IAwsToken idToken = authenticationService.Tokens.IdToken; //This is the code that calls "RefreshTokens" method
........
}
catch (Exception ex)
{
//Code never reaches here...
_logger.Error("Error in ProcessMessage", ex);
}
_processingCounter.Decrement();
}
这是一个async void
。 避免使用异步void方法的主要原因之一是您无法处理它们引发的异常。
将其设为async Task
,然后在调用await
它。
请注意,然后在该调用async void Process(...)
存在相同的问题, async void Process(...)
也将其设为async Task
,然后async Task
。 从GUI或Controller到异步I / O调用,异步/等待应该形成一个链。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.