I'm a long time Java developer, but with so little traffic on SE, I don't limit my viewing to any single tags. I've noticed that C# questions with async/await come up a lot, and as far as I've read it's the standard (but somewhat recent) asynchronous programming mechanism in C#, which would make it equivalent to Java's Executor
, Future
or perhaps more accurately CompatibleFuture constructs (or even wait()/notify()
for very old code).
Now async / await seems like a handy tool, quick to write and easy to understand, but the questions give me the feeling that people are trying to make everything async, and that this isn't even a bad thing.
In Java, code that would attempt to offload work to different threads as often as possible would seem very odd, and real performance advantages come from specific well thought out places where work is divided to different threads.
Is the discrepancy because of a different threading model? Because C# is often desktop code with a well known platform under it, whereas Java is mainly server side these days? Or have I just gotten a skewed image of its relevancy?
From https://markheath.net/post/async-antipatterns we have:
foreach(var c in customers)
{
await SendEmailAsync(c);
}
as an example of acceptable code, but this seems to suggest "make everything asynchronous, you can always use await
to synchronize". Is it because the await
already indicates that there's actually no reason to switch threads, whereas in Java
for(Customer c : customer) {
Future<Result> res = sendEmailAsync(c);
res.get();
}
would actually perform the work in a different thread, but get()
would block, so it would be sequential work, but using 2 threads?
Of course with Java, the standard idiom would be to let the caller decide whether something needs to be async, rather than having the implementation decide it in advance E.g.
for(Customer c : customer) {
CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> sendEmailSync(c));
// cf can be further used for chaining, exception handling, etc.
}