Explain how async waits again

This is my event handler code:

protected async void TestrunSaveExecute()
{
    bool saveResult = await SaveTestRunAsync();
}

To maintain responsiveness of the user interface, I used the async/ method await.

In my understanding, now I can perform some lengthy operations in SaveTestRunAsync()without blocking the user interface, since it is decoupled using a keyword await.

private async Task<bool> SaveTestRunAsync()
{
    //System.Threading.Thread.Sleep(5000); --> this blocks the UI
    await Task.Delay(5000); // this doesn't block UI

    return true;
}

Could you explain why the call Thread.Sleepstill blocks the user interface, but Task.Delaynot?

0
source share
4 answers

The code still runs in the user interface thread.

It does not work in the background thread.

, , , - .

Thread.Sleep .

, async await.

await :

. - , await. - , .

, , , await Task.Delay(5000);. " 5 " " , ". , .

5 .

, , -, , , , .

, ?

Task.Run.

, , .

, await :

Life of method:    <------------------------------------------------------->
Parts:             [ start of method ----][awaitable][ rest of method -----]

, , await X, , X , , Task , awaitable , " " .

X , , -, , , await .

, . , ( ) , .

, " ", , , " " , ( ) .

await , , , .

Task, .NET. async/await , , , .

+14

, SaveTestRunAsync() , .

async/await , " " . , await, , ( ), await .

Thread.Sleep Task.Delay , , . , Timer . , , ( - , )

+2

, "" ( , , ), , , "" ( ). , .

, ( ), , .

, . "" Task.Run()

+1

Async/await - , .

async, ( ) .

, Thread.Sleep , async/await .

: SynchronizationContext.

0