我有一個(gè)引用以下代碼的 Windows 服務(wù)。使用下面的方法,我的代碼包含一個(gè)try..catch塊,但它似乎并沒有catch RefereshTokenException認(rèn)為是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); }}這是調(diào)用的代碼 RefreshTokenspublic 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();}
1 回答

郎朗坤
TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是一個(gè)async void
. 避免異步 void 方法的主要原因之一是您無法處理它們拋出的異常。
在調(diào)用者中使它成為一個(gè)async Task
和await
它。
請注意,您隨后在該呼叫者中遇到了相同的問題, async void Process(...)
把它做好,然后async Task
按照自己的方式工作。async/await 應(yīng)該形成一個(gè)鏈,從您的 GUI 或控制器到異步 I/O 調(diào)用。
- 1 回答
- 0 關(guān)注
- 147 瀏覽
添加回答
舉報(bào)
0/150
提交
取消