Task Factory and Task Parallelism Parallel Library in C#

I’m hoping all is good in your life. Here is a brief explanation of the Task Factory and Task Parallelism Parallel Library in C#.

What do a Task Factory and Task Parallelism exactly mean?

Task parallelism is the process of running a task right after it has been created. does the operation in a certain sequence. Task Factory is the name given to the kind of execution.

Let’s now examine Task Parallelism in more detail

  • Task parallel library is used to perform the asynchronous operations.
  • The task that is invoked by Task Parallelism is invoked by being independent of one another.
    Parallel.Invoke(() => Console.WriteLine("Perform Action 1"), () =>Console.WriteLine("Perform Action 2"));
  • Task.Run method A task can be created and started in a single operation, or step.
  • TaskFactory.StartNew can also be used to create and launch a task simultaneously.

Examples

TaskFactory.StartNew 
  • Used when we don’t require return type and taking so much time to execute your request we don’t want the required user can wait till task done like following operations mail sending, exception log and etc.
    Task.Factory.StartNew(SendContactUsMail(MailModel obj));
Task Parallelism
  • Child Tasks Associated With A Parent Task
    class TaskParallelism
    {
        static void Parallelism(string[] args)
        {
            Task<int[]> parentTasks = new Task<int[]>(() =>
            {
                var results = new int[3];
                new Task(() => {
                    Thread.Sleep(15000);
                    results[0] = 0;
                },
                TaskCreationOptions.AttachedToParent).Start();
                new Task(() => results[1] = 1,
                TaskCreationOptions.AttachedToParent).Start();
                new Task(() => results[2] = 2,
                TaskCreationOptions.AttachedToParent).Start();
                return results;
            });
            parentTasks.Start();
            var finalTask = parentTasks .ContinueWith(
            parentTask => {
                foreach (int i in parentTask.Result)
                    Console.WriteLine(i);
            });
            finalTask.Wait();
            Console.ReadLine();
        }
    }

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories