Friday 17 March 2017

Threading 02 ParameterizedThreadStart

Before we created a thread that takes a parameterless method, now there's also the option of passing in a method with a parameter, the only restriction is that parameter has to be of type object. not a big deal since everything can be boxed or cast as one.

using System;
using System.Collections.Generic;
using System.Threading;

namespace pc.threadingExample
{
    class Program
    {
        static void LongRunningMethod(object name)
        {
            Thread.Sleep(5000);
            Console.WriteLine($"Hello {(string)name}");
        }
        static void Main(string[] args)
        {
            char inputChar;
            var threads = new List<Thread>();
            do
            {
                Console.WriteLine("1)say hi \n0)exit\n");
                inputChar = Console.ReadKey().KeyChar;
                if (inputChar == '1')
                {
                    var t = new Thread(LongRunningMethod);
                    t.IsBackground = true;
                    t.Start("pawel");
                    threads.Add(t);
                }

            } while (inputChar != '0');

            foreach (var t in threads)
            {
                Console.WriteLine($"thread:{t.ManagedThreadId} joining");
                t.Join();
            }
        }
    }

}

as you see we just add an object parameter to our long running thread and pass the object in as a parameter when we start our thread, everything else we talked about still holds true.

now full disclosure time odds are you'll never be creating threads but instead you'll use either the async/await keywords or the TPL task parallel library.