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).
No,
awaitis not like just callingget(). There’s considerably more to it.When you use an
awaitexpression 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 theawaitexpression, you’ll continue on the UI thread afterwards, but without blocking the UI thread while you’re waiting for the result. For example: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: