user156144 user156144 - 11 months ago 69
C# Question

c# async runs single threaded?

I was reading
Example code:

async Task<int> AccessTheWebAsync()
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();

// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("");

// You can do work here that doesn't rely on the string from GetStringAsync.

// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;

// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;

The page also says:

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread

Does this "no additional thread is created" applies within scope of the method marked as async?

I would imagine in order for both GetStringAsync and AccessTheWebAsync to be running at the same time (otherwise GetStringAsync will never finish as AccessTheWebAsync has control now), eventually GetStringAsync has to run on a different thread from AccessTheWebAsync's thread.

To me, writing async method is only useful at not adding more thread when the method it awaits is also async (which already use extra thread to do its own thing in parallel)

Is my understanding correct?

Answer Source

This is the key to the power of async. GetStringAsync and other naturally-asynchronous operations do not require a thread. GetStringAsync just sends out the HTTP request and registers a callback to run when the server replies. There's no need for a thread just to wait for the server to respond.

In reality, the thread pool is used just a tiny bit. In the example above, the callback registered by GetStringAsync will execute on a thread pool thread, but all it does is notify AccessTheWebAsync that it can continue executing.

I have an async intro blog post you may find helpful.