Page 130 - CSharp/C#
P. 130
Any usual method can be turned into async in the following way:
await Task.Run(() => YourSyncMethod());
This can be advantageous when you need to execute a long running method on the UI thread
without freezing the UI.
But there is a very important remark here: Asynchronous does not always mean concurrent
(parallel or even multi-threaded). Even on a single thread, async-await still allows for
asynchronous code. For example, see this custom task scheduler. Such a 'crazy' task scheduler
can simply turn tasks into functions which are called within message loop processing.
We need to ask ourselves: What thread will execute the continuation of our method
DoIt_Continuation?
By default the await operator schedules the execution of continuation with the current
Synchronization context. It means that by default for WinForms and WPF continuation runs in the
UI thread. If, for some reason, you need to change this behavior, use method
Task.ConfigureAwait():
await Task.Run(() => YourSyncMethod()).ConfigureAwait(continueOnCapturedContext: false);
Returning a Task without await
Methods that perform asynchronous operations don't need to use await if:
• There is only one asynchronous call inside the method
• The asynchronous call is at the end of the method
• Catching/handling exception that may happen within the Task is not necessary
Consider this method that returns a Task:
public async Task<User> GetUserAsync(int id)
{
var lookupKey = "Users" + id;
return await dataStore.GetByKeyAsync(lookupKey);
}
If GetByKeyAsync has the same signature as GetUserAsync (returning a Task<User>), the method can
be simplified:
public Task<User> GetUserAsync(int id)
{
var lookupKey = "Users" + id;
return dataStore.GetByKeyAsync(lookupKey);
}
In this case, the method doesn't need to be marked async, even though it's preforming an
https://riptutorial.com/ 76

