What the author says here is that simply using async keywords and waiting does not cause the current method to run in another thread. Let's look at what happens in the provided code.
async Task<int> AccessTheWebAsync() {
Everything up to this point has been running in a single thread. At this point, calling client.GetStringAsync can unscrew the new thread (although this is not guaranteed for any async method). It should be noted, however, that the GetStringAsync method essentially starts this current thread (for example, it actually makes a call), but the response will be read in another thread after it returns. This is represented by returning a Task object. A task can be an already completed bit of work, a current executable secondary thread, or a block of work that is simply scheduled to be completed later.
DoIndependentWork();
Now this is done in our main thread after the call has been queued (or possibly sent). Therefore, this can happen while waiting for a request to be returned. Please note that we are still in our main topic.
string urlContents = await getStringTask;
At this point, our thread returns ..NET will create a continuation function containing the rest of the method (return urlContents.Length;), which will be automatically called for us as soon as getStringTask completes its own thread. At this point, the new thread will pick up a sequel.
Thanks to all this, everything that we wrote in our async method, up to the wait keyword, was performed in one thread. Of course, we called another method that could happen to create another thread, but we did nothing to create another thread, just using the async / await keywords. The continuation at the end can be called, perhaps, another thread, but after our initial function really returned (thatβs why our function returns a Task object to represent work that may not finish when any calls to this function return).
source share