Avoiding Deadlock with HttpClient

后端 未结 3 1569
失恋的感觉
失恋的感觉 2021-01-03 10:57

What is the best way to use HttpClient and avoid deadlock? I am using the code below, called entirely from synchronous methods, but I concerned it maybe causing

3条回答
  •  一向
    一向 (楼主)
    2021-01-03 11:28

    In my case, when I used await client.GetAsync(), I didnot receive any response, when I tried to observe the problem, the debugger also terminated on the above GetAsync() line. I could only use client.GetAsync().Result to get the reponse correctly, but I saw many saying that it may lead to deadlock like in this post and it is synchronous too. I was particularly using this in UI button click event as well, which is not recommended.

    Finally, I got it working by adding the below three lines, I didnot have those three lines before (maybe that was the problem):

    using (var client = new HttpClient())
    {    
      string relativeURL = "api/blah";
      //These three lines - BaseAddress, DefaultRequestHeaders and DefaultRequestHeaders
      client.BaseAddress = new Uri(Constants.ServiceBaseAddress);
      client.DefaultRequestHeaders.Clear();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      HttpResponseMessage response = await client.GetAsync(relativeURL);
      ...
    }
    

    NOTE:

    1. The ServiceBaseAddress must end with slash (/) and relative URL must begin without slash (/)
    2. Sample of my Constants.ServiceBaseAddress is https://domainname.org/

    This is working fine now, with async signature and no deadlock worries. Hope this helps somebody.

提交回复
热议问题