Two new keywords added to the C# 5.0 language are async and await, both of which work hand in hand to run a C# method asynchronously without blocking the calling thread.
My question is, do these methods actually take advantage of multiple cores and run in parallel or does the async method run in the same thread core as the caller?
Two new keywords added to the C# 5.0 language are async and await, both of which work hand in hand to run a C# method asynchronously without blocking the calling thread.
That gets across the purpose of the feature, but it gives too much "credit" to the async/await feature.
Let me be very, very clear on this point: await
does not magically cause a synchronous method to run asynchronously. It does not start up a new thread and run the method on the new thread, for example. The method you are calling has to be the thing that knows how to run itself asynchronously. How it chooses to do so is its business.
My question is, do these methods actually take advantage of multiple cores and run in parallel or does the async method run in the same thread core as the caller?
Again, that is entirely up to the method you call. All that await
does is instruct the compiler to rewrite the method into a delegate that can be passed as the continuation of the asynchronous task. That is, the await FooAsync()
means "call FooAsync()
and whatever comes back must be something that represents the asynchronous operation that just started up. Tell that thing that when it knows that the asynchronous operation is done, it should call this delegate." The delegate has the property that when it is invoked, the current method appears to resume "where it left off".
If the method you call schedules work onto another thread affinitized to another core, great. If it starts a timer that pings some event handler in the future on the UI thread, great. await
doesn't care. All it does is makes sure that when the asynchronous job is done, control can resume where it left off.
A question you did not ask but probably should have is:
When the asynchronous task is finished and control picks up where it left off, is execution in the same thread as it was before?
It depends on the context. In a winforms application where you await something from the UI thread, control picks up again on the UI thread. In a console application, maybe not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With