Tuesday 4 April 2017

TPL 01 Simple tasks

Threads are expensive, complicated, and at times unpredictable leaving you at the whims of the operating system. In .Net 4.0 the TPL Library was introduced to simplify the process of adding parallelism and concurrency to applications. The task parallel library introduces the Task class, this class abstracts away threads, it simplifies the process of creating asynchronous code.

Tasks unlike the threadpool work items not only have the ability to notify the user upon completion, but tasks can also return a response. Tasks are created via the "Task Scheduler"; the task scheduler is responsible for starting and managing the task, by default it uses the thread pool to create tasks.

here's a simple parameterless task without a return type

using System;
using System.Threading.Tasks;

namespace pc.tplExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var t1 = new Task(() =>
            {
                var td = Task.Delay(1000);
                Task.WaitAll(td);
                Console.WriteLine($"Hello from task 1");
            });
            t1.Start();

            var t2 = Task.Factory.StartNew(() => {
                var td = Task.Delay(500);
                Task.WaitAll(td);
                Console.WriteLine($"Hello from task 2");
            });

            Task.WaitAll(t1, t2);
        }
    }
}


now this just demonstrates a simple way of creating, starting and waiting for tasks, we could also utilize a static WaitAny function on our Task class.