I have been reading about c# async methods in the past 2 days and from what I understand, unlike in a thread (threadpool.queueuserworkitem()), a call to an async method does not return immediately and it only returns when the called method hits an await or complete(or exception)
Please see the following example.
public partial class MainWindow : Window
{
// . . .
private async void startButton_Click(object sender, RoutedEventArgs e)
{
// ONE
Task<int> getLengthTask = AccessTheWebAsync();
// FOUR
int contentLength = await getLengthTask;
// SIX
resultsTextBox.Text +=
String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
}
async Task<int> AccessTheWebAsync()
{
// TWO
HttpClient client = new HttpClient();
Task<string> getStringTask =
client.GetStringAsync("http://msdn.microsoft.com");
// THREE
string urlContents = await getStringTask;
// FIVE
return urlContents.Length;
}
}
From what I gather, in the above code, AccessTheWebAsync() is called synchronously(i.e. control does not return immediately when it is called). But in the line named 'THREE', the runtime will return control.
My questions are:
How does the runtime decide when to use the threadpool or when to run the task in the calling thread? (i.e. execute the code without returning control)
At which points in the above code, new threads (or thread pool) will be used?
If
AccessTheWebAsync()did something computationally intensive, like running a loop with a zillion iterations, the control will only return to the caller when the loop is completed. Is that right?In an async function, is there a way to return the control immediately and then continue doing the work in say a background thread? (just like if we called threadpool.queueuserworkitem())
Is calling an async method without an await in it (assume it s possible) same as calling a non async method?