Skip to main content

Task Parallel Library


Problem: One of the clients was running the multi threaded application on a single core machine, he upgraded his system to Quadra-core and he observed that the application did not improve or started degrading the performance. The development team later found the reason that applications were not utilizing the benefits of cores and it was still running in single core. Solution: .Net 4.0 has brought a new Task Parallel library which uses the benefits of multi core. The Library efficiently utilizes the system resources to give better performance. Internally it uses Threadpool with improved algorithm with .Net 4.0

NamespaceSystem.Threading.
Tasks Class - Task

Create Task
Task t1 = new Task(() => Add(1,100));
t1.Start();
t1.Wait(); //Wait till task t1 is completed and then starts t2 Task
t2 = new Task(() => Add(101, 200));
t2.Start();

//Other way of creating multiple task
var tasks = new Task[2];
tasks[0] = Task.Factory.StartNew(() => Add(1, 100));
tasks[1] = Task.Factory.StartNew(() => Add(101, 200));
Task.WaitAll(tasks);

Create Dependency of Task
//Add and then display no’s and see output without creating Dependency
var tasks1 = new Task[4];
tasks1[0] =Task.Factory.StartNew(() => Add(1, 50));
tasks1[1] =Task.Factory.StartNew(() => Add(101, 150));
tasks1[2] =Task.Factory.StartNew(() => Display());
tasks1[3] =Task.Factory.StartNew(() => Display());

//Add and then display no’s and create dependency for sequential display
var tasks1 = new Task[4];
tasks1[0] =Task.Factory.StartNew(() => Add(1, 50));
tasks1[1] =Task.Factory.StartNew(() => Add(101, 150));
// start after completing adding of tasks1
tasks1[2] =tasks1[0].ContinueWith((t) => Display());
// start after completing tasks1[2]
tasks1[3] =tasks1[2].ContinueWith((t) => Display());

Cancel Running Task
For Cancelling a task following steps need to be performed:

1. Create Method with input parameter of Cancellation token and check for IsCancellationRequested Property of token to display the message that task is cancelled

public static void CancelProcess(CancellationToken ct)
{
      Thread.Sleep(1000);
      if (ct.IsCancellationRequested)
     {
         Console.WriteLine("Process cancelled");
     }
}

2. Create token:

      var source = new CancellationTokenSource();
      var token = source.Token;

3. Create task and call the CancelProcess method, also pass the token to the method
      var taskCancel = Task.Factory.StartNew(() => CancelProcess(token), token);

4. Cancel the token source on User's request:
      source.Cancel();

Comments

Popular posts from this blog

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete Univ...

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         ...

SSIS package - set oledb connections at runtime

SSIS oledb connection manager does't allow user to connect to different oledb servers. If we store oledb connection sting in Config file then it will accepts server name, InitialCatalog and username. But it wont accept password. The is because oledb connection manager has not exposed the oledb password property. To over come this problem we have to override the OLEDB connection manager itself. So that it accepts connections to different oledb servers. Public Sub Main() Dim vars As Variables Dim oledbConnectionManager As ConnectionManager oledbConnectionManager = Dts.Connections("<oledb connection name>") ' ADDED TO MAKE oledb CONNECTION STRING DYNAMIC Dim oServerName As String Dim oUserName As String Dim oInitialCatalog As String Dim oPassword As String Dts.VariableDispenser.LockOneForWrite("oServerName", vars) oServerName = vars("oServerName").Value.ToString().Trim() vars.Unlock() Dts.VariableDispenser.LockOneForWrite("oInitia...