Skip to main content

Extending WhenAny,WhenAll like feature to get the task as soon as it completes

While working with list of task, we only get two built in options to retrieve task info for completion. First is WhenAny and other WhenAll. WhenAny can be used when any of the given tasks gets completed first where as WhenAll notifies when all of the task gets completed. There is no option to know each task as soon as it gets completed.

I was going through Pro Asynchronous Programming with .NET book which shows better option to deal with notification of task completion efficiently.

To return the task on completion, TaskCompletionSource will be used . Through TaskCompletionSource, Task could be created and with provided inbuilt methods outcome can be handled. This can be also helpful to wrap up legacy codes as well to built up task.

Let's directly look in to core code to return task based on completion.

 /// <summary>  
     /// Order by completion for Task.  
     /// </summary>  
     /// <typeparam name="T">Return type</typeparam>  
     /// <param name="tasks">The tasks.</param>  
     /// <returns></returns>  
     /// <exception cref="System.ArgumentNullException">tasks</exception>  
     /// <exception cref="System.ArithmeticException">Must have at least one task</exception>  
     public static IEnumerable<Task<T>> OrderByCompletion<T>(this IEnumerable<Task<T>> tasks)  
     {  
       if (tasks == null)  
       {  
         throw new ArgumentNullException("tasks");  
       }  
       var allTasks = tasks.ToList();  
       if (!allTasks.Any())  
       {  
         throw new ArithmeticException("Must have at least one task");  
       }  
       // Create list of TaskCompletionSource  
       var taskCompletionSources = new List<TaskCompletionSource<T>>(allTasks.Count);  
       for (int tskCtr = 0; tskCtr < allTasks.Count; tskCtr++)  
       {  
         taskCompletionSources.Add(new TaskCompletionSource<T>());  
       }  
       int nextCompletdTask = -1;  
       for (int nTask = 0; nTask < allTasks.Count; nTask++)  
       {  
         taskCompletionSources[nTask] = new TaskCompletionSource<T>();  
         allTasks[nTask].ContinueWith(tsk =>  
         {  
           // Thread safe increment of variable  
           int taskToComplete = Interlocked.Increment(ref nextCompletdTask);  
           switch (tsk.Status)  
           {  
             case TaskStatus.Canceled:  
               taskCompletionSources[taskToComplete].SetCanceled();  
               break;  
             case TaskStatus.Faulted:  
               // InnerException is used to avoid AggregateException  
               taskCompletionSources[taskToComplete].SetException(tsk.Exception.InnerException);  
               break;  
             case TaskStatus.RanToCompletion:  
               taskCompletionSources[taskToComplete].SetResult(tsk.Result);  
               break;  
           }  
         }, TaskContinuationOptions.ExecuteSynchronously);  
       }  
       return taskCompletionSources.Select(src => src.Task);  
     }  

In the above code at first, list of TaskCompletionSource created based on number of tasks. Afterwards, task continuation is done for each task and result of task is transformed with the help of methods from TaskCompletionSource.

You might worried about TaskContinuationOptions.ExecuteSynchronously .This is on task continuation and the block of code just composing task which is perfectly fine and it won't block the code.

Now above extension function can be attached with any list of task by using OrderByCompletion. Let's see with example:

     private static void Main(string[] args)  
     {  
       var uriList = new List<string>()  
       {  
         "http://www.google.com",  
         "http://www.yahoo.com",  
         "http://www.msn.com",  
         "http://www.bing.com",  
         "http://vikutech.blogspot.in",  
       };  
       var tasks = GetDownloadedContentTaskAsync(uriList);  
       foreach (var task in tasks.OrderByCompletion())  
       {  
         Console.WriteLine(task.Result);  
       }  
     }  
     /// <summary>  
     /// Gets the downloaded content asynchronous as task.  
     /// </summary>  
     /// <param name="urlString">List of URLs.</param>  
     /// <returns>Content of downloaded string</returns>  
     private static IEnumerable<Task<string>> GetDownloadedContentTaskAsync(IEnumerable<string> urlStrings)  
     {  
       foreach (var url in urlStrings)  
       {  
         var client = new WebClient();  
         yield return client.DownloadStringTaskAsync(new Uri(url));  
         // TODO: Check sequence of program sequence  
         //yield return Task<string>.Factory.StartNew(() =>  
         //{  
         //  Task.Delay(4000);  
         //  return url;  
         //});  
       }  
     }  

The code is creating list of task and looping it to get the results from task when any task is getting completed in any sequence.
Source code: https://www.dropbox.com/s/9xemmci3ey40qug/TaskCompletionSequence.zip

Popular posts from this blog

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques tha…

LDAP with ASPNet Core Identity in MVC Core

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

AspNet Identity Core is a new offering from Microsoft in replacement of AspNet Identity for managing users.

In this tutorial, we would be looking for implementing LDAP with AspNet Identity Core to allow users to be able to log in through AD or AspNet Identity Core members.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functiona…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

Startup.cs
public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…