Tuesday 8 November 2016

.Net High Performance Part 1 : The Task Object for Async programming

Coming back to the blogging after long months of idling ( From blogging though :) ).

Ok guys, things would be going on in a different direction from this point  on wards and I would be concentrating on more focused areas rather than blogging everything I learn freshly.  So folks , the focused areas are HPC ( High Performance Computing )  on .Net and Secure Software Development ( Well, Security would be my future as I see it now :D )

The HPC mainly categorized into 2 areas such as Async programming and Parallel Programming. Async Programming mainly concerns about application responsiveness and improve user experience. Technically, fork high latency , blocking operations in to different app thread.

The Parallel programming mainly focusing on performance by reducing the time of CPU-bound computations.

 One way of achieving this Parallelism is using Tasks in the .Net realm. A Task is considered as a unit of work or an object denoting an ongoing operation or computation.

Following is the basic steps to create a Task object and delegate the computationally time consuming process into a different application thread.


 
using System.Threading.Tasks;

Task T = Task.Factory.StartNew(() =>
{
 Random rand = new Random();
 int start = System.Environment.TickCount;

 double result= Simulation.ComputeComplex(rand);

 int stop = System.Environment.TickCount;

 double elapsedTimeInSecs = (stop - start) / 1000.0;

 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

}
);

This code would delegate the complex process execution to a different thread than the Application UI thread. But there is a problem. Accessing the lblResult from a non UI thread is illegal and throwing an exception. To counter this we need to create a ContinueWith block using the T object and let the UI content update after the complex operation thread.
 
using System.Threading.Tasks;

Task T = Task.Factory.StartNew(() =>
{
 Random rand = new Random();
 int start = System.Environment.TickCount;

 result= Simulation.ComputeComplex(rand);

 int stop = System.Environment.TickCount;

 elapsedTimeInSecs = (stop - start) / 1000.0;

 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

}
);

T.ContinueWith((antecedent) =>
{
 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

 
 TaskScheduler.FromCurrentSynchronizationContext()
);


No comments:

Post a Comment