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
Namespace: System.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
Post a Comment