2

I am working on a winforms application with async methods. On an event i call multiple series of async methods. Unfortunately, the application freezes. My async calls are all awaited but i couldnt figure out what caused the deadlock.

Winforms block

    private async void sendMessages_Click(object sender, EventArgs e)
    {
         await ServiceFacade.SendMessage("Hi to CEO");
         await ServiceFacade.SendMessage("Hi to Manager");
         await ServiceFacade.SendMessage("Hi to Team Leader");
    }

My library class which sends data to an api

   public class ServiceFacade
   {

   public  async Task SendMessage(string message)
   {

       //validates and formats message then calls PostAsync to send it on api service

       await PostAsync(string message);
   }

   private static async Task PostAsync(string message)
   {

       HttpWebRequest request = (HttpWebRequest)WebRequest.Create("hostname.com")
       //set up REQUEST ...
       var response = (HttpWebResponse)await request.GetResponseAsync();
   }

   }
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
Jicking
  • 768
  • 6
  • 12
  • @musefan i waited for about 30mins an my app is still freezed. i also set my request to 60 seconds. – Jicking May 17 '17 at 12:49
  • On the off chance that your actual code is more complicated, are you using Task.Wait() anywhere within the async flow? It sounds like you're aware of this already, so I assume not. – ProgrammingLlama May 17 '17 at 13:06
  • @john i did not since it will block the context. all of my tasks are awaited. i am so puzzled how this resulted on deadlock. – Jicking May 17 '17 at 13:17
  • Just to confirm, I've reproduced it at my end, but I'm unsure why it's happening. I'll see what I can find out :) – ProgrammingLlama May 17 '17 at 13:17
  • [Here](https://github.com/Microsoft/referencesource/blob/master/System/net/System/Net/WebRequest.cs#L898-L931) is the source code for WebRequest. – ProgrammingLlama May 17 '17 at 13:20
  • "Offload to a different thread to avoid blocking" will setting await be enough? im new to async/await :( – Jicking May 17 '17 at 13:29
  • You want to know something weird? If I only make two requests in a row, it works... it gets stuck on the third one. – ProgrammingLlama May 17 '17 at 13:42
  • 1
    It seems related to the accepted answer here (increasing the max connections allowed all of my requests to operate): http://stackoverflow.com/questions/1361771/max-number-of-concurrent-httpwebrequests - I suspect there's a bug when you're using it asynchronously which prevents it from returning an error / waiting correctly. I'd recommend switching to HttpClient (I've experienced none of these issues with it.) – ProgrammingLlama May 17 '17 at 13:48

0 Answers0