代码之家  ›  专栏  ›  技术社区  ›  CrazyCoder

如何知道从哪一点触发HttpClient任务取消

  •  0
  • CrazyCoder  · 技术社区  · 7 年前

    public async Task<HttpResponseMessage> SendHttpRequest()
    {
        HttpResponseMessage response = null;
        try
        {
            HttpClient client = new HttpClient();
            string accessToken = await GetBearerToken(resourceUrl, clientId, clientSecret, tokenProviderUrl);
            if (!string.IsNullOrEmpty(accessToken))
                httpRequest.Headers.Add("Authorization", ("Bearer " + accessToken));
    
            response = await client.SendAsync(httpRequest);
        }
        catch(Exception ex)
        {
            log.Error("Exception raised while sending HTTP request");
            log.Error("Exception details : " + ex.Message);
        }           
    
        return response;
    }
    
    public async Task<string> GetBearerToken()
    {           
        HttpResponseMessage response = null;
        HttpClient client = new HttpClient();
        string token = "";
        try
        {
            var request = new HttpRequestMessage(HttpMethod.Post, tokenProviderUrl);
            request.Content = new FormUrlEncodedContent(new Dictionary<string, string> {
                { "client_id",clientId},
                { "client_secret", clientSecret },
                { "grant_type", "client_credentials" },
                { "resource", resource },
            });
    
            response = await client.SendAsync(request);                
            var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
            token = payload.Value<string>("access_token");                
        }
        catch (HttpRequestException ex)
        {
            log.Error("Error in GetToken : " + ex.Message.ToString());
        }
        return token;
    }
    

    我在这里面临的问题是,有时,这段代码会抛出一个异常,说“Task was cancelled”(任务被取消了),但不是每次都这样。我在网上搜索过 this

    奇怪的是,任务等待30分钟(或者我们指定的任何超时),然后抛出task was cancelled异常,这让我抓狂。

    我想知道为什么当我们不明确地重新请求任务时,任务会被取消,任务会从谁或哪里被取消?有没有办法找到取消申请的来源?

    请假设所有变量都有正确的值,尽管这里没有提到。

    异常消息:

    任务已取消。

    这是异常堆栈跟踪:

    异常堆栈跟踪:位于 任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务)在 System.Net.Http.HttpClient.dúu58.MoveNext() ---从引发异常的上一个位置的堆栈结束跟踪-- 任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 在SampleProject.dúu 2.MoveNext()中 ---从引发异常的上一个位置的堆栈结束跟踪---

    0 回复  |  直到 7 年前