簡體   English   中英

被取消的任務

[英]Task in getting canceled

我這個服務從兩個地方獲取令牌,並將每個 HTTP 請求中的令牌作為 header 附加。 我不知道為什么,但我收到了這個錯誤。 我正在處理異步,但這個任務仍然被取消。

public class TokenService : DelegatingHandler, IHostedService
    {
        public IConfiguration Configuration { get; }
        private Timer _timer;
        public IHttpClientFactory _clientFactory;
        protected HttpClient _client_SB;
        protected HttpClient _client_Opsman_SB;
        private readonly IServiceScopeFactory _scopeFactory;
        string connectionString = "";

        public TokenService(IConfiguration configuration, IHttpClientFactory clientFactory, IServiceScopeFactory scopeFactory)
        {
            Configuration = configuration;
            _clientFactory = clientFactory;
            _scopeFactory = scopeFactory;
            connectionString = Configuration.GetConnectionString("DefaultConnection");
            _client_SB = _clientFactory.CreateClient("TestEnv");
            _client_Opsman_SB = _clientFactory.CreateClient("OpsmanTestEnv");
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(GetAccessToken, null, 0, 3300000);
            _timer = new Timer(GetAccessTokenOpsMan, null, 0, 3300000);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            //Timer does not have a stop. 
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
        {
            HttpClient client = new HttpClient();
            FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);
            HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
                throw new ApplicationException(message);
            }

            string responseString = await response.Content.ReadAsStringAsync();
            Token token = JsonConvert.DeserializeObject<Token>(responseString);

            return token;
        }
        private void GetAccessToken(object state)
        {
            Dictionary<string, string> authenticationCredentials_sb = Configuration.GetSection("TestEnvironment:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
            Token token_sb = GetToken(new Uri(Configuration["TestEnvironment:URL"]), authenticationCredentials_sb).Result;

            _client_SB.DefaultRequestHeaders.Add("Authorization", $"Bearer {token_sb.AccessToken}");
        }

        private void GetAccessTokenOpsMan(object state)
        {

            Dictionary<string, string> authenticationCredentials_opsman_sb = Configuration.GetSection("OpsManTestEnvironment:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
            Token opsman_token_sb = GetToken(new Uri(Configuration["OpsManTestEnvironment:URL"]), authenticationCredentials_opsman_sb).Result;
            _client_Opsman_SB.DefaultRequestHeaders.Add("Authorization", $"Bearer {opsman_token_sb.AccessToken}");
        }
    }

未處理的異常:System.AggregateException:發生一個或多個錯誤。 (任務被取消。)---> System.Threading.Tasks.TaskCanceledException:任務被取消。 --- 內部異常堆棧跟蹤結束 --- 在 c:\agent_Work09\73\s\ 中 ProjectEcho.Services.TestService.GetAccessTokenOpsMan(Object state) 的 System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) Services\TestService.cs:System.Threading.ExecutionContext.RunInternal 的第 73 行(ExecutionContext executionContext,ContextCallback 回調,Object 狀態)--- 從先前拋出異常的位置結束堆棧跟蹤---在 System.Threading.TimerQueueTimer。 CallCallback() 在 System.Threading.TimerQueueTimer.Fire() 在 System.Threading.TimerQueue.FireNextTimers() }

您將需要查看內部異常,您只是報告 AggregateException 但這只是真正的 INNER 異常的包裝。

catch (AggregateException agg_ex)
{
   //just get first exception, it will contain the most relevant error.
   var ex = agg_ex.InnerExceptions[0];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM