Not a long ago C# has introduced special language constructs to simplify asynchronous programming. It seems C++1x will follow async trend. But only recently when frameworks like ASP.NET Web API and Entity Framework started to catch up we've felt how it's to program with async and await keywords.
async
await
At first glance it seems it's a pure pleasure to write async methods:
private async Task SumPageSizesAsync() { // To use the HttpClient type in desktop apps, you must include a using directive and add a // reference for the System.Net.Http namespace. HttpClient client = new HttpClient(); // . . . byte[] urlContents = await client.GetByteArrayAsync(url); // . . . }
To dereference a Task<T> into T you just write await task_t_expression, mark your method with async specifier, and adjust output type (if not void) to Task or Task<Result>. Compiler applies its magic to convert your code into an asynchronous state machine.
Task<T>
T
await task_t_expression
void
Task
Task<Result>
We liked this feature and immediately have started to use it. But, as we said, async/await has shined in full when frameworks made it a core element, and at that point we have started to see that while async/await solve the task, they does not abstract the developer from implementation details, as a code gets considerably polluted.
Consider a method with pollution marked:
public static async Task<UserAuthorization> GetAuthorizationAsync(string accessToken) { var key = "oauth2:" + accessToken; var authorization = cache.Get<UserAuthorization>(key); if (authorization != null) { return authorization; } using(var model = new ModelContainer()) { authorization = (await model.UserAuthorizations. Where(item => item.AccessToken == accessToken). ToListAsync()). FirstOrDefault(); } if (authorization == null) { authorization = await ValidateAsync(accessToken); } cache.Set(key, cache.ShortDelay, authorization); return authorization; }
The more you use async, the more pollution you will see in your code. Ideally we would like to see the method quoted without any marked parts.
Remember Me
a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u