Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding how Async and Await works c#

i saw some post regarding Async and Await usage in this site. few people are saying that Async and Await complete its job on separate background thread means spawn a new background thread and few people are saying no means Async and Await does not start any separate background thread to complete its job.

so anyone just tell me what happen in case of Async and Await when it is used.

here is one small program

class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

And the output is:

Starting Long Running method...
Press any key to exit...
End Long Running method...
like image 359
Mou Avatar asked Dec 03 '22 16:12

Mou


1 Answers

The problem is that async/await is about asynchrony, not threads.

If you use Task.Run, it will indeed use a background thread (via the Thread Pool, via the Task Parallel Library).

However, for IO operations it relies on IO Completion ports to notify when the operation is complete.

The only guarantee async/await makes is that when an operation completes, it will return to your caller in the SynchronizationContext that was there when it began. In practical terms, that means it will return on the UI Thread (in a Windows application) or to a thread that can return the HTTP Response (in ASP.NET)

like image 177
Richard Szalay Avatar answered Dec 16 '22 15:12

Richard Szalay