Tasks

Running more than one task in parallel can be achieved using the Task Parallel Library (TPL) that was introduced in .NET 4.0.
This library contains the following features:


  • Data and task parallelism

  • Schedule threads in a thread pool

  • Ability to use all available cores

  • Cancellation of work

  • Partitioning of work


A task is a lightweight object that manages a parallelism unit of work
Tasks use the CLRs thread pool which avoids creating a new thread.


Task Class

This is a replacement for the ThreadPool.QueueUserWorkItem



Task<Result> Class

This is the generic version of the Task class
This is a replacement for the asynchronous delegates



Creating Tasks

For non generic task classes we call Task.Factory.StartNew and we pass in a delegate of the target method



System.Threading.Task myTask = new System.Threading.Task( () => Console.WriteLine("My new task") ); 
myTask.Start();

Alternatively you could use this line to create and start in one operation

System.Threading.Task.Factory.StartNew( () => Console.WriteLine("My new task") ); 


Task Creation Options


LongRunning
PreferFairness
AttachedToParent



© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext