C# Understanding the TASK class

C# Understanding the TASK class .

=======================================================
The Task Object typically executes asynchronously on a Thread Pool thread rather than synchronously on the main Thread.IsCanceled,IsCompleted,IsFaulted,Status property are being used
to determine the state of a TASK.Most Commonly Lambda expression is used to specify the work that task is to perform.
Task instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static Run method. The Run method provides a simple way to start a task using default values and without requiring additional parameters.


 TaskFactory.StartNew --> Is a method to start a task in .NET 4
 Task.Run()         -->  Is a method to start a task in .NET 4.5  
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ManualResetEvent_
{
    /* class Threading
     {
         static int s_value;
         public static void run()
         {
             s_value = 42;
             Task T = Task.Factory.StartNew(() => { Console.WriteLine(s_value); });
             T.Wait();
         }


     }

     class Employee
     {
         public string name { get; set; }
         public int salary { get; set; }
         public int d{get;set;}
     }

     class program
     {
         public static void Main()
         {
             /* Stepes to initialize or create object only when it is required */
    /*Employee employee=null;
    Console.WriteLine(employee);
    if (employee == null)
    {
        employee = new Employee();
        Console.WriteLine(employee);
    }*/

    /* Stepes to initialize or create object only when it is required with Lazy Initializer */
    /*Lazy<Employee> emp=new Lazy<Employee>();
    Console.WriteLine(emp);
    emp.Value.name = "Mishra";
    emp.Value.salary = 3000;
    Console.WriteLine(emp);
    Console.ReadLine();

               
}
}*/
    public class Example
    {
        public static void Main()
        {
            Task T = Task.Run(() =>
            {
                int i = 0;
                for (i = 0; i < 10; i++)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("I am sleeping again for 1 sec");
                }
                Console.WriteLine(" I cam out of my sleep");
                Console.ReadLine();
            }
                              );
            T.Wait();
        }


    }
}

Difference between Task and Thread

===================================
Task is a promise to do something asynchronously and thread is a way of caring out that task.In fact creating a thread is often undesirable because doing so is much more expesive than reusing
an existing thread from the threadpool.If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread to sit around and waitfor the data when it can be servicing other requests. Instead the Task might register a callback to receive the values when they are ready.
Task are scheduled on a threadpool and could even be executed synchronous if appropiate.
Synchronous execution of tasks is called inilining. When scheduling a taskon the threadpool(default scheduler) from the UI('TaskScheduler.current') is the same as the schedular of a task you call 'Wait()'
on .As 'Wait()' is blocking, it will be blocking the UI anyway.
Short: Don't call wait and it will not be executed synchronously. The thread pool job is to share and recycle threads . It allows to avoid losing a few milisecond every time we need
to creat a new thread . There are several ways to enter the thread pool.
1) With the TPL (Task Parallel Library) like you did
2) by calling Threadpool.QueueUserWorkItem
3) by calling BeginInvoke on a delegate
4) when you use a Backgroungworker

The Task Class also provides constructors that initialize the task but that do not schedule it for executions
For performance reason the Task.Run or TaskFactory.StartNew method is the preferred mechanismfor creating and scheduling computational tasks but for scenarios where creaion and scheduling must be separated you can use the constructor and then call the Task.Start method to schedule the task for execution at a later time.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Threading;
namespace AsyncAwaits
{
public calss Asyncprocessiong
    {
    static void Main()
    {
    Task T=Task.Factory.StartNew(()=>
    {
    Console.Writeline("Please let me sleep for sometime");
    System.Threading.Thread.Sleep(8000);
    Console.WriteLine("hey I have slept for 8 sec");});
    /* T.wait actually waits for the task to get completed and then continue executing the main with out which the main will finish
    executing and then Task will produce the out out */
    T.Wait();
    Console.WriteLine("Now I am awake");
    Console.ReadLine();
    }}}

Basics
====================================================================================================
using System;
using System.threading.Tasks
using System.Threading;
namespace AsyncAwaits
    public class Asyncprocessing
    {
    static void Main()
    {
    Task task1=new Task(()=>Console.WritelLine("I will be executing from the thread {0} and I belong to task{1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
    });
    Console.WriteLine("I am the Main Thread {0}, and I have forked {1}",Thread.CurrentThread.ManagedThreadId,Task.CurrentId);
    task1.Start();
    task1.Wait();
    Console.ReadLine();
    }
    }
    }
====================================================================================================   
   
using System;
using System,Collections.Generics;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Threading;

namespace AsynAwaits
{
    public class Asyncprocessing
    {
    static void Main()
    //Different ways of starting a TASK from a threadpool
    //To perform a simple task create a new instance of the task class, passing in a System.Action Delegate
    //that represents the workload that you want to performed as a constructor argument
    //You can explicilty create the action delegate so that it refers to a named method
    //use a anonymous function, or use a lambda function . Once you have created an instanceof Task, call the start() method and your Task is then passed to the task schedular

    TaskT1=new Task(new Action(Display_my_message)); //Using Action Delegate and named method
    T1.Start();
    Task T2=new Task(delegate {Displcay_my_message();}); //Using anonymous delegate
    T2.Start();
    Task T3=new Task(()=> Display_my_message()); //Using Lambda Expresion
    T3.Start();
    Task4 = new Task(()=> {Console.Writeline("I am directly executing from the lambda expression");});
    T4.Start();                //Lambda Expression and an anonymous method
    Console.WriteLine("Completed exepression");
    Console.ReadLine();
    }
   
    public static void Display_my_message()
    {
    Console.WriteLine("I will be executing for Task");
    }
    }
    }

Few Video links
http://channel9.msdn.com/blogs/bruceky/how-to-parallelize-your-application-part-2-threads-v-tasks
http://channel9.msdn.com/blogs/bruceky/how-to-parallelize-your-application-part-3-using-tasks


UnderStanding Action<T> delegate
======================================================================
If encapsulate a method that has single parameter and doesn't return any value
For more reference check:
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task%28v=vs.110%29.aspx
public delegate void Action<in T>
    {
T obj
}

in T ----> the type of the parameter of the method that this delegate encapsulates
Obj t ----> Type T, The parameter of the method that this delegate encapsulates.


Likewise we can have Action<in T1,in T2> ( for Encapsulation a method that has two parameters and does not return a value)
similarly Action<in T1,in T2,in T3> ( for Encapsulate a method that has three parameters and does not return a value)


======================================================================
Using action delegate to display a message
---------------------------------------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.generics;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Threading;

namespace AsyncAwaits
    {
    static void Main()
    {
    Action<object> action =(object obj) =>
                    {
                    Console.Writeline("Task={0} , obj ={1} , Thread ={2}", Task.CurrentId,obj,Thread.CurrentThread.ManagedThreadID);
                    };
    Task Task1= new Task(action,"Task1");
    Task Task4= Task.Factory.StartNew(()=>{Console.Writeline("Task={0}",obj={1},Thread={2}", Task.CurrentId,"Task4",Thread.CurrentThread.ManagedThreadId);
                    });
    Task4.Wait();
    //This take a thread friim the threadpool and execute after its completed execution the thread is release back to thread pool//
    Task Task2= Task.Factory.StartNew(action,"Task2");
    Task2.Wait();
    //This may or may not take the same thread from the threadpool as was doen by the previous
    Task1.Start();
    Console.WriteLine("Task1 Task is launched on the Main Thread: {0}", Thread.CurrentThread.ManagedThreadId);
    Task1.Wait();
    //This will run on the main Thread as can be seen from the values Thread.CurrentThread.ManagedThreadId
    Task Task3= new Task(action,"Task3");
    Task3.RunSynchronously();
    Task3.Wait();
    Console.ReadLine();
    }
    }
    }

Note : the order of execution of the threads are Task4->Task2->Task1->Task3
   
}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6