If the async method is single, how can it be run in the background?

I am trying to understand async / await and have read a number of articles, but I am still confused about the synchronous / asynchronous nature.

I have the following test console application:

static void Main(string[] args)
{
    var test = FooAsync();
    Console.WriteLine("After FooAsync");

    for (int i = 0; i < 100; i++)
        Console.WriteLine("After that");

    Console.ReadKey();
}

private static async Task FooAsync()
{
    Console.WriteLine("Before delay");
    await Task.Delay(1);
    Console.WriteLine("After delay");
}

      

The code outputs line by line:

Before delay
After FooAsync
After that
After that
After that
After that
After delay
After that
.
.

      

I understand that async / await will not create a separate thread to process and that at the point a FooAsync

line appears await Task.Delay(1)

, it will Main

fall back to , since the task has not finished yet since we are only running on one thread, can anyone explain what causes the method FooAsync

to run in which -or an arbitrary point inside Main

before Main

can continue?

Update I am bringing it back and i3arnon and dariogriffo are correct. The code uses multiple threads (as I've seen before, looked in the debugger, or did the obvious as ha suggested). I was confused by the "Themes" section on the next page https://msdn.microsoft.com/en-us/library/hh191443.aspx#BKMK_Threads , not realizing that "continuation" actually refers to the continuation task scheduling starts as soon as the pending task ends.

+3


source to share


3 answers


It's not a one-liner .

When the delay task is complete, the rest of the method is dispatched to ThreadPool

and run at the same time as your main thread. The "trigger" here is an internal callback System.Threading.Timer

that is used internally Task.Delay

.



It depends SynchronizationContext

. In a UI environment, this would be sent to the same UI thread and would have to wait until that thread is free.

If you were waiting for jobs returned from FooAsync

then you will only have one thread running each time.

+5


source


Async / await can create new threads OR NOT, it depends on the nature of the operation. If the IO operation (like disk / network operations) is probably coded in such a way that it won't spin a new thread. You can read here:

Async and pending keywords don't create additional threads?

If you create your own Async operation and you create a thread it is a different story why you shouldn't do async synchronization



http://blogs.msdn.com/b/pfxteam/archive/2012/04/13/10293638.aspx

You can also check this, but using Thread.CurrentThread to get the process id. (Add this to Console.WriteLine)

+2


source


It is a fairly common misconception that keywords async

or await

create new streams. They don't.

Threads are created at startup Task

. In this case, the thread is created by calling Task.Delay

.

0


source







All Articles