Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use static method/classes within async/await operations?

It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.

Now async/await has been introduced into the c# 4.5+ framework - which simplifies multithreaded applications and encourages responsive UI.

However - as a lock cannot/should not be placed over an awaiting method (and I'm not debating that) does that now make static methods utilizing async/await completely redundant?

like image 749
Patrick McCurley Avatar asked Oct 24 '12 09:10

Patrick McCurley


People also ask

Why you shouldn't use async void?

Async void methods can wreak havoc if the caller isn't expecting them to be async. When the return type is Task, the caller knows it's dealing with a future operation; when the return type is void, the caller might assume the method is complete by the time it returns.

Should you always await async methods?

If a method is declared async, make sure there is an await! If your code does not have an await in its body, the compiler will generate a warning but the state machine will be created nevertheless, adding unnecessary overhead for an operation that will actually never yield.

Does async await use thread pool?

Await Keyword Basically, it returns to caller thread with reference to ongoing task and stop execution of code below that line and release the current thread to thread pool to process another request. Async and await are always used together, if not, then there will be something wrong.

What happens if we execute an asynchronous method but don't await it?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.


1 Answers

It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.

Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:

public static async Task<int> GetPageLength(string url) {     string text = await new WebClient().DownloadStringTaskAsync(url);     return text.Length; } 

If you do have shared state - or if you're in an instance method on an instance which is used by multiple threads - you need to work out how you would ideally want your asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.

like image 95
Jon Skeet Avatar answered Sep 16 '22 16:09

Jon Skeet