Thursday, November 27, 2014

Task In C#


Task in very simple terms represents a asynchronous operation , Task type was introduced in .net framework 4.0   as a part of TPL(task parallel library) ,if you are working with WINRT Api's  we can see these Task Types  as a return type for  most of the APi's with supports async and await keywords.

What is the difference between Threads and Tasks? 

  • Threads are very expensive (both on memory ,CPU time , Context switching )to create and to clean up  
  • Running code in a task does not mean a new thread instead Task use the thread pool shipped with  the .net framework,the framework manages the available cores to provide  best possible output .this is not available with thread where we developers have to manage every thing. 
  • Threads work in a single core but Task best suited to utilize multiple core.
  • Easier Exception Handling in case of Tasks

How to create a task ?

Task in its simplest form can be created as below:
// if you asre working with .NET Framework 4 
Task.Factory.StartNew(() => { Console.WriteLine("I am being run by Task "); });

//if you are working with .NET Framework 4.5 and above 
 Task.Run(() => { Console.WriteLine("I am being run by Task "); });

Once the task is started the code block after that will continue to run, Check; the below code

static void Main(string[] args)
        {

          var theTask =  Task.Run(() => {
              // simulating a long running task 
              Thread.Sleep(10000);
              Console.WriteLine("I am run by Task"); });
     Console.WriteLine("is my task complted ::"+theTask.IsCompleted);
     Console.WriteLine("last line of code now the application will exit");
        }
in the above code the app will exit even before the task is completed.

How to wait for a task to complete?

All this needs is a one line of code(Task.Wait()) as show below
 static void Main(string[] args)
        {
          var theTask =  Task.Run(() => {
              // simulating a long running task 
              Thread.Sleep(3000);
              Console.WriteLine("I am run by Task"); });
     Console.WriteLine("is my task complted ::"+theTask.IsCompleted);
          theTask.Wait();
     Console.WriteLine("is my task complted ::" + theTask.IsCompleted);
     Console.WriteLine("last line of code now the application will exit");
        
        }

How to Return a value from task?

Every task that is initiate either gives you back a task object or any of its  Generics sub classes  Task<TResult>, using this  Task object you can track the status of the Running tasks ,check is its completed get the result from the task if  there is any return type also also easily check if the task failed , all these features are given out of the box in  with Task and it is very tedious to build this feature when working with Threads .

Below is a  simple code snippet which returns a simple string :

      //Returns the task object which represents the task that is initiated
       static Task ReturnTask()
        {
            Task theTask = Task.Run(() =>
            {
                // simulating a long running task 
                Thread.Sleep(3000);
                Console.WriteLine("I am run by Task");
                return  "I am done with the task";
            });
            return theTask;            
        }
     // you get the reference to the task object 
     Task checkTask = ReturnTask();

// when you want to get  the result all you need to  do 
// query the task object and get the result if ready 
 void ReadResult(Task taskObject) 
        {
            bool isTaskCompleted = taskObject.IsCompleted;
            if (isTaskCompleted)
            {
                Console.WriteLine("task Completed with the result ::" + taskObject.Result);
            }

        }
** There is lot more explore

  • Imperative Data Parallelism (Involves using Parallel for,foreach and Invoke )
  • Declarative Data Parallelism(PLINQ)

0 comments:

Post a Comment