Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

Any kind of async operation freezes

I was trying to get the source of a web page async, and actually this is what I have done thousands of time before. it is working when it is not async, but it freezes whenever I try to make it async.

I tried:

await new WebClient().DownloadStringAsyncTask();

Using WebRequest inside

await Task.Run(() =>
{

});

Using new WebClient().DownloadString() inside

await Task.Run(() =>
{

});

Using HttpClient.GetAsync();

And they were all failing. When I traced inside Task.Run() I noticed that the operation actually works, gets the result and completes however after completion it never returns. I tested even with empty Task.Run() just like below:

await Task.Run(() =>
{

});

and still it doesn't return? Is it a bug in .NET Framework 4.8? Why a simple code that I have used thousands of times stop working?

By the way, it is a Winforms Application.

Upvotes: 0

Views: 736

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

The code calling into this async code is blocking on this task's completion (via .Result or .Wait()). The Winforms Task Scheduler is assuming that your task needs to continue on the same thread it started from, but that thread is waiting for your Task to complete, putting you in a deadlock.

One solution is to remove the blocking code upward in your call stack, and go "async all the way". (It sounds like this will require refactoring async logic out of your constructor, which I highly recommend anyway).

Another would be to use .ConfigureAwait(false) consistently before all of your awaits that don't need to continue on the same thread they started from.

Another would be to put the Task.Run(...) call into the part of the code that's blocking, so it explicitly blocks on a different thread.

Upvotes: 3

Related Questions