Saturday, June 28, 2014

Learn how to use threads in C#

For some odd reason, the article I wrote about loving C# yesterday sparked a flurry of emails asking me about threading. So I thought I'd write a quick and dirty tutorial on how to write multithreaded applications in C#. It's not going to be enterprise-class software, but it should give you a good enough idea to get you started.

First, what is multithreading?

Multithreading is the process of running multiple instructions on a computer at the exact same time. Today's computers often have 4-8 cores which means you can execute 4-8 instructions at the same time by using multithreading programming concepts.  That often (but not always) means your software will do things faster because it can chew through data and instructions at a more rapid rate that a single threaded application.

How about an example?

The code below is a simple example of how to write a multithreaded application in C#. It's not complex and you should be able to figure it out but we'll walk through it once we're done anyway.

using System;
using System.Threading;

namespace AMulthreadedApplicationExample
{
    class ThreadedProgram
    {
        public static void MyChildThread()
        {
            Console.WriteLine("Hello World from thread #2!");
        }
        
        static void Main(string[] args)
        {
            ThreadStart childthrd = new ThreadStart(MyChildThread);
            Console.WriteLine("Hello World from thread #1!");
            Thread childThread = new Thread(childthrd);
            childThread.Start();
            Console.ReadKey();
        }
    }
}
Much of this code should already be familiar to you as it's all part of a standard C# program. So let's look specifically at the MyChildThread() method and a few statements in the Main() method.

As you can see, the MyChildThread() method is nothing special. It's just a standard method that gives no hint that it's going to be run in a multhreaded way. All the magic happens in the Main() method and it's pretty easy to understand.

First, we define a ThreadStart delegate called 'childthrd' and pass the name of the method we want to execute in the new thread to its constructor. In the third line we actually create the new thread, passing the ThreadStart delegate in the constructor of the new thread. Finally, We execute the new thread with a call to the Thread.Start() method. This last line of code is what actually starts (or schedules to start) the new thread that executes the MyChildThread() method.

Once started, threads usually run to their end and then gracefully die. But there might be times that you want to explicitly kill a thread before it finishes executing. This too is amazingly easy. To kill a thread prior to its completion you simply use the Thread.Abort() method and it kills it. It's that simple. 

While this is not, by any stretch of the imagination, an exhaustive look at threads, it should be enough for you to start doing your own research. Threads are a powerful way to write high performing software and, once you learn them, you'll find all sorts of situations where they come in handy.

Happy multitasking!







































No comments: