Friday, April 3, 2015

Task Parallelism Usage Pattern using Async in ASP.NET

1) Use a list of tasks

var tasks = new List<Task<string>>
{
      CreateHtmlTextFirstAsync(),
      CreateHtmlTextSecondAsync(),
      CreateHtmlTextLastAsync()
};

2) Process tasks if any left in a while loop, removing completed task within the loop.
     Keep flushing out the completed contents of each task as it completes in the loop.
     (Note: Commenting out the check for IsFaulted that would not display content if the task had faulted, as this check may not be correctly coded here)

context.Response.ContentType = "text/html";
context.Response.Write(@"<!DOCTYPE html><html><body>");
context.Response.Write(@"<title>Async Body Sections!</title>");

while (tasks.Any())
{
      var completed = await Task.WhenAny(tasks);
      task.Remove(completed);
   
      //if (!completed.IsFaulted)
      //{
            context.Response.Write(completed.Result);
            context.Response.Flush();
     // }
}

context.Response.Write(@"</body></html>");

**********************************************

We can improve the above code further by making the Response.Flush run asynchronously.
There is no async method for it, but we can make use of Task class like so and make it awaitable:

await Task.Factory.FromAsync(context.Response.BeginFlush, context.Response.EndFlush, null);


No comments:

Post a Comment