DEV Community

Discussion on: Async / Await: From Zero to Hero

Collapse
 
bellonedavide profile image
Davide Bellone

Nice post! I also had troubles approaching async programming, so I wrote an article to help other devs understand the basics of this topic: code4it.dev/blog/asynchronous-prog...

Collapse
 
zhiyuanamos profile image
Zhi Yuan • Edited

Hey Davide, thanks for reading! I read through your article and found out about the existence of ValueTask, thanks for writing!

A quick comment on the header How to make a sync method asynchronous: Correct me if I'm wrong, I think such a scenario is only helpful when developing Desktop applications, whereby heavy synchronous work should not be processed by the UI thread, but deferred to a background thread using Task.Run.

Web applications, however, do not have a UI thread. Consider the code samples below (the first is copied from your article)

// Suppose Thread A is processing this incoming request
var taskResult = Task.Run( () => DoSomethingSynchronous() ); // Thread B is assigned to process DoSomethingSynchronous()
int value = await taskResult; // Thread A is freed up to process other incoming requests

VS

DoSomethingSynchronous(); // processed by Thread A

In both scenarios, a thread is required to perform DoSomethingSynchronous(); there's no benefit in doing it in an asynchronous manner. Rather, the asynchronous code would be slightly less performant as it has to deal with the overhead of async/await and allocating Thread B to execute DoSomethingSynchronous() and freeing Thread A.

Edit: I think it's beneficial to run synchronous methods on separate threads using Task.Run when executing multiple expensive synchronous methods. For example:

SomeExpensiveSynchronousMethodOne();
SomeExpensiveSynchronousMethodTwo();

VS

var taskOne = Task.Run(() => SomeExpensiveSynchronousMethodOne());
var taskTwo = Task.Run(() => SomeExpensiveSynchronousMethodTwo());
await Task.WhenAll(taskOne, tasktwo);

In the first option, the methods run sequentially, while the second option has both methods running in parallel, thus the second option should complete earlier than the first option.