Tuesday, 11 April 2017

TPL 02 Tasks with parameters

Tasks like threads can only receive objects as parameters, they can be declared inline or passed in as parameters

using System;
using System.Threading.Tasks;

namespace pc.tplExample02
{
    class Program
    {
        static Random rnd = new Random(DateTime.Now.Millisecond);
        static void Main(string[] args)
        {
            var t1 = new Task(name => {
                Console.WriteLine($"{name} started");
                Task.WaitAll(Task.Delay(rnd.Next(1000, 2000)));
                Console.WriteLine($"{name} finished");
            }, "Pawel");
            t1.Start();

            var t2 = Task.Factory.StartNew(name =>
            {
                Console.WriteLine($"{name} started");
                Task.WaitAll(Task.Delay(rnd.Next(1000, 2000)));
                Console.WriteLine($"{name} finished");
            }, "Magda");

            var t3 = Task.Factory.StartNew(MyTask, "Marin");
            var t4 = Task.Factory.StartNew(MyTask, "Jakub");

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

        static void MyTask(object o) {
            Console.WriteLine($"{o} started");
            Task.WaitAll(Task.Delay(rnd.Next(1000, 2000)));
            Console.WriteLine($"{o} finished");
        }
    }
}


Above is a simple example where we cast a string as an object and just leverage the native string classes toString() method, however we could have passed a struct as a parameter and just boxed and unboxed it.

using System;
using System.Threading.Tasks;

namespace pc.tplExample02
{
    class Program
    {
        static Random rnd = new Random(DateTime.Now.Millisecond);

        struct Data
        {
            public string Name { get; private set; }
            public string Task { get; private set; }
            public Data(string Name, string Task)
            {
                this.Name = Name;
                this.Task = Task;
            }
        }
        static void Main(string[] args)
        {
            var t1 = Task.Factory.StartNew(MyTask,
                new Data("Pawel", "Task A"));
            var t2 = Task.Factory.StartNew(MyTask,
                new Data("Magda", "Task B"));
            var t3 = Task.Factory.StartNew(MyTask,
                new Data("Marin", "Task C"));
            var t4 = Task.Factory.StartNew(MyTask,
                new Data("Jakub", "Task D"));

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

        static void MyTask(object o)
        {
            var d = (Data)o;
            Console.WriteLine($"{d.Name} started");
            Task.WaitAll(Task.Delay(rnd.Next(1000, 2000)));
            Console.WriteLine($"{d.Name} finished");
        }
    }
}


just like we worked with threads passing an object in as a parameter