异步异常未被捕获

时间:2018-05-23 06:20:16

标签: c# asynchronous

我有一个引用以下代码的Windows服务。我使用以下方法的代码包含catch块,但在下面的方法中,它RefereshTokenException thrown似乎不是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(); }

的代码
<html>

<div id = "tag">

</div>

<script>
function createSelect2(tag) {
var select = document.createElement("select");
var opt1 = document.createElement("option");
var opt2 = document.createElement("option");

opt1.value = "return 0;";
opt1.text = "YES";
opt1.title = "YES!"

opt2.value = "return 1231 * area;";
opt2.text = "NO!";
opt2.title = "NO!"

select.add(opt1, null);
select.add(opt2, null);

tag.appendChild(select);
}

createSelect2(document.getElementById("tag"));
</script>

</html>

1 个答案:

答案 0 :(得分:5)

这是async void。避免异步void方法的一个主要原因是您无法处理它们抛出的异常。

在来电者中将其设为async Taskawait

请注意,您在该来电者async void Process(...)

中遇到了同样的问题

让它成为async Task并继续前进。 async / await应该形成一个链,从GUI或Controller到异步I / O调用。