danielsen / NetSPF

.NET SPF tools
MIT License
2 stars 3 forks source link

Never wrap sync code in a new task #4

Closed StephanMoeller closed 1 year ago

StephanMoeller commented 2 years ago

You should not wrap sync code in

public async Task MyAsyncMethod() { int value = await Task.Run(() => DoSomeSyncCodeThatReturnsAnInt()); return int; }

This method will just add another task to pool and when that task runs it will block the thread. This should just be done the following way:

public async Task MyAsyncMethod() { int value = DoSomeSyncCodeThatReturnsAnInt(); return int; }

The two methods above will block equally much, but the latter has less overhead. There is nothing wrong with calling something sync, if there is no real async version of the call needed. But wrapping the sync call in a task does not make it true async.