Vlad's blog

In programming veritas

Archive for November 2014

async/await in C#

leave a comment »

Concurrency is mandatory part of almost every modern application. In .Net TPL provides solid foundation for organizing different scenarios of asynchronous communication. Starting from MSVS 2012 we have two new keywords to deal with concurrent methods: async and await.

As example consider client server remote communication. The Server maintains a list of jobs that Client must execute. Once client is successfully authorized it starts retrieving jobs one by one. When a job is finished the Client asks the Server to remove this job from the list and retrieves the next job. All communication between Server and Client is asynchronous because the nature of communication protocol. But the logic is definitely sequential:

  • Authorize
  • Retrieve first job
  • Execute first job
  • Finalize first job on the Server
  • Retrieve the next job

We want to update the UI in non blocking fashion. So if authorization takes 3 seconds the UI should be responsible. Below is the implementation of sample Authentication service. It just adds a delay to simulate server side processing.

public class AuthenticationService
   public Task<bool> Authenticate()
     return Task.Delay(TimeSpan.FromSeconds(3)).ContinueWith(t => true);

Read the rest of this entry »


Written by vsukhachev

November 24, 2014 at 1:21 pm

Posted in Development

Tagged with