Mvc: An issue about "async/await“ and ”Task.WaitAll“ in the asp.net core.

Created on 8 Mar 2018  ·  4Comments  ·  Source: aspnet/Mvc

Following is the trouble codes:

```c#
public async Task Test()
{
try
{
var taskA = GetTask();

        Task.WaitAll(taskA);   //<--- wating.. wating.... wating......

        return 0;     //<---- Unreachable
    }
    catch (Exception ex)
    {
        return -1;
    }

}

```c#
public async Task<int> GetTask()
{
        return await Task.Run(() =>
        {
            Thread.Sleep(1500);
            return 1;
        });
 }

ConsoleApp .netfx4.5 :No problem.

Asp.net Webapi .netfx4.5 :The taskA will always be in an uncompleted state.

Most helpful comment

This looks like the classic deadlock problem; basically you mustn't use .Result or .Wait in ASP.Net as it may cause a deadlock. The explanation why is a bit complex, but if you Google async deadlock you will find explanations.
I did think, though, that ASP.Net Core had changed that behaviour. Did you mean to refer to Core or "Classic"?

All 4 comments

This looks like the classic deadlock problem; basically you mustn't use .Result or .Wait in ASP.Net as it may cause a deadlock. The explanation why is a bit complex, but if you Google async deadlock you will find explanations.
I did think, though, that ASP.Net Core had changed that behaviour. Did you mean to refer to Core or "Classic"?

Thanks a lot. I had tried it in Core. It had no problem. Deadlock, Yes, deadlock~

Hi @NMSLanX. You shoud avoid blocking code as much as possible. Can you please replace the Task.WaitAll(taskA); with await Task.WhenAll(taskA); instead and see whether that solves the problem?

@mkArtakMSFT Thank you!

Was this page helpful?
0 / 5 - 0 ratings