The Task Parallel Library explains the concept of "Task". It executes Tasks in parallel way. It has great advantages over thread and thread pool. This library has been released in version 4.0 of the .NET framework.
The following are some benefits of using Tasks:
- It uses system resources more efficiently.
- It provides more programming control than threads.
- It also includes other concept like Future. Future returns result.
Namespace
- using System.Threading.Tasks
Creating Tasks with different ways
1. Direct and common way
- #region Most Direct Way
-
-
-
-
- public void MostDirectWay()
- {
- Task.Factory.StartNew(() => { Console.WriteLine("Most Direct and Common way to create thread."); });
- }
-
- #endregion
2. Task using with Action
- #region Thread using Action
-
- public void ThreadUsingAction()
- {
- Task task = new Task(new Action(PrintMessage));
- task.Start();
- }
-
- private void PrintMessage()
- {
- Console.WriteLine("Thread using Action.");
- }
-
- #endregion
3. Task using Delegates
- #endregion
-
- #region Thread using Delegate
-
- public void ThreadUsingDelegate()
- {
- Task task = new Task(delegate { PrintMessageForDelegateThread(); });
- task.Start();
- }
-
- private void PrintMessageForDelegateThread()
- {
- Console.WriteLine("Task Creation using Delegate");
- }
-
- #endregion
4. Tasks using Lambda and named method:
- #region Thread using Lambda and named method
- public void ThreadUsingLambda()
- {
- Task task = new Task(() => PrintMessageMessageForLambda());
- task.Start();
- }
-
- private void PrintMessageMessageForLambda()
- {
- Console.WriteLine("Task with Lambda");
- }
-
- #endregion
5. Task using Lambda and anonymous method:
- #region Lambda and anonymous method:
-
- public void TaskUsingLambdaAndAnonymousMethod()
- {
- Task task = new Task(() => Console.WriteLine("Task with Anonymous Method"));
- task.Start();
- }
-
- #endregion
6. Creating and running Tasks Implicitly:
Tasks are created and maintained implicitly by the framework. It is used when developer needs to process Tasks which do not return any value and no more control is required.
The Parallel.Invoke method provides a best way to run any number of arbitrary statements concurrently. It creates Tasks implicitly.
- #region Create Task implicitly using Parallel.Invoke
-
- public void ImplicitTaskWithParallel()
- {
- Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());
- }
-
- private void DoSomeOtherWork()
- {
- Console.WriteLine("Execute second Tasks");
- }
-
- private void DoSomeWork()
- {
- Console.WriteLine("Execute First Task");
- }
-
- #endregion