Reputation: 2064
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?
Upvotes: 48
Views: 123549
Reputation: 1503290
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.
Upvotes: 82