Sunday, 16 April 2017

TPL 03 Task with return types

Now for something tangible that tasks bring to the table and that's return types.

using System;
using System.Threading.Tasks;

namespace pc.tplExample03
{
    class Program
    {
        static void Main(string[] args)
        {
            var t1 = new Task<int>(() => {
                var rnd = new Random(DateTime.Now.Millisecond);
                var result = rnd.Next(1000,2000);
                Task.WaitAll(Task.Delay(result));
                return result;
            });
            t1.Start();

            //wait for result
            int randomInt = t1.Result;

            Console.WriteLine(randomInt);
        }
    }
}

in the above function we create a task that returns a value, we can couple this with our parameter example from before

using System;
using System.Threading.Tasks;

namespace pc.tplExample03
{
    class Program
    {
        static Random rnd = new Random(DateTime.Now.Millisecond);
        static void Main(string[] args)
        {
            int result = Task.Factory.StartNew<int>(Square, 5).Result;
            Console.WriteLine(result);
        }

        static int Square(object o)
        {
            int num = Convert.ToInt32(o);
            int delay = rnd.Next(1000, 5000);
            Task.WaitAll(Task.Delay(delay));
            return num * num;
        }
    }
}

basically the same thing as before but this time we pass a parameter with our func, however we are still restricted by calling the result property; calling the result property of a task halts the calling thread until the task returns.