Thursday, October 12, 2017

C# multithreading

C# multithreading is a pretty straightforward thingy. Here is how we spawn a thread:

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(){}

        static void Main(string[] args)
        {
            Thread thread = new Thread(Whatever);

            thread.start();
        }
    }
}

using System;
using System.Threading;

namespace ConsoleApp
{
    class Dummy
    {
        public void Whatever(){}
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dummy dummy = new Dummy();
            Thread thread = new Thread(dummy.Whatever());

            thread.start();
        }
    }
}

Thread class constructor accepts two types of delegate - ThreadStart and ParametrizedThreadStart. The difference between the two is that ParametrizedThreadStart allows us to pass some arbitrary object to a thread function like this:

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(object obj){}

        static void Main(string[] args)
        {
            Thread thread = new Thread(Whatever);

            thread.Start("Whatever");
        }
    }
}

If your project requires massive parallelism, it probably makes sense to try using so-called thread pool which is basically nothing more than a collection of dormant threads you can reuse.

using System;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Whatever(object obj)
        {
            (obj as ManualResetEvent).Set();
        }

        static void Main(string[] args)
        {
            ManualResetEvent[] events = new ManualResetEvent[2];

            for (int i = 0; i < events.Length; ++i)
            {
                events[i] = new ManualResetEvent(false);

                ThreadPool.QueueUserWorkItem(Whatever, events[i]);
            }

            WaitHandle.WaitAll(events);
        }
    }
}



No comments:

Post a Comment