Chi-Lan Chi-Lan - 2 months ago 37
C# Question

Differences between C# async and Java ExecutorService

C# has a cool new feature

public Task<string> async f()
{
string r = LongCompute();
return r;
}


but isn't that equivalent to

public Future<String> f() {
return Globals.executorService.submit(new Callable<String>() {
public String call() throws Exception {
String r = longCompute();
return r;
}
});
}


where in Java you have more flexibility to choose the threadpool in which the task would run.

What about await? It's equivalent to just calling get

string s = await f();


is just like

String s = f().get();


Is there anything more to C#, or is it indeed just a syntactic sugar to the Java version? (I'm not a C# guru, so I might be missing something).

Answer

No, await is not like just calling get(). There's considerably more to it.

When you use an await expression in C#, the compiler effectively creates a continuation, so that if the awaitable hasn't completed yet, the method can immediately return, and continue processing only when it's completed. The continuation will run in an appropriate context - so if you're on a UI thread before the await expression, you'll continue on the UI thread afterwards, but without blocking the UI thread while you're waiting for the result. For example:

public async void HandleButtonClick(object sender, EventArgs e)
{
    // All of this method will run in the UI thread, which it needs
    // to as it touches the UI... however, it won't block when it does
    // the web operation.

    string url = urlTextBox.Text;
    WebClient client = new WebClient();
    string webText = await client.DownloadStringTaskAsync(url);

    // Continuation... automatically called in the UI thread, with appropriate
    // context (local variables etc) which we used earlier.
    sizeTextBox.Text = string.Format("{0}: {1}", url, webText.Length); 
}

Ultimately it's all syntactic sugar, but much more complicated sugar than what you've shown.

There's a lot of detailed information available on the web already. For example:

Comments