Search code examples
c#nito.asyncex

Running into deadlocks code using AsyncContext


This is my code, I'm using AsyncEx in my library to try to get around potential deadlocks, but I ended up in there anyway:

return AsyncContext.Run(async () =>
{
   var get = await httpClient.GetAsync(url);
   if (get.IsSuccessStatusCode && (get.StatusCode == HttpStatusCode.OK))
   {
      var content = await get.Content.ReadAsStringAsync();
      return content;
   }

   return "";
});

I'm running this from a command line app, calling it with multiple different url values in a row, but synchronously in one big for loop. Given enough calls, it will eventually stop dead in its tracks. Am I doing something wrong?


Solution

  • What I think happens is that after calling GetAsync the continuation cannot switch back to the same thread since the other thread is waiting for the continuation to start. Does the following code work?

    return AsyncContext.Run(async () =>
    {
       var get = await httpClient.GetAsync(url).ConfigureAwait(false);
       if (get.IsSuccessStatusCode && (get.StatusCode == HttpStatusCode.OK))
       {
          var content = await get.Content.ReadAsStringAsync().ConfigureAwait(false);
          return content;
       }
    
       return "";
    });