How To Work With Multithreaded Programming In C#.NET Application


 How To Work With Multithreaded Programming In C#.NET Application  
 


While working with desktop application development, we may sometimes required to work with Multithreaded programming. It can also help in optimizing the performance of the software as it make most usage of the CPU core(s) and thus providing better throughput/results. We refer to this type of implementation as ‘multi-tasking’ also. As in such case, our application will be able to do different type of tasks at the same time, in parallel.

For Example, just consider a simple database based desktop application development scenario, where your application will retrieve a series of data and show to user. Now, if the database connectivity is slow for some reason, your application will normally get stuck. User won’t be able to do anything else but wait for the process to be finished. In such cases, we can nicely design a thread based implementation, which will allow user to do other actions while your application is retrieving data from a database, and improves the usability in a large-scale.

A simple classic thread Example:

Lets start with a very simple single thread example.The following code examples will show a simple thread running strategy. The thread will run 50 times with an interval of 500 milliseconds between each running.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart testThreadStart = new ThreadStart(new Program().testThread);
            Thread testThread = new Thread(testThreadStart);

            testThread.Start();
            Console.ReadLine();
        }

        public void testThread()
        {
            //executing in thread
            int count = 0;
            while (count++ < 50)
            {
                Console.WriteLine("Thread Executed "+count+" times");
                Thread.Sleep(500);
            }
        }
    }
}

As you can see, first we need to define a ‘ThreadStart’ instance with the function that we will need to be executed in thread. Then, this instance are required as parameter in our ‘Thread’ class initialization. After calling the ‘start’ method, the function will be called for execution in parallel to other processes.

Also, remember that, the function will be called only once. to keep it alive is our own responsibility. That means, we will need to run it inside a for loop until it satisfy a certain criteria. The ‘Sleep’ method waits that particular thread for the given amount of time(in milliseconds) before executing next statement.

Multithreaded Programming With Classic Threads:

Lets move one step ahead to see how more than one threads can be run in parallel. Following code snippet will demonstrate such scenario. Though, I am using two threads only here, you can add as many you want to it as per your need.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart testThread1Start = new ThreadStart(new Program().testThread1);
            ThreadStart testThread2Start = new ThreadStart(new Program().testThread2);

            Thread[] testThread = new Thread[2];
            testThread[0] = new Thread(testThread1Start);
            testThread[1] = new Thread(testThread2Start);

            foreach (Thread myThread in testThread)
            {
                myThread.Start();
            }

            Console.ReadLine();
        }

        public void testThread1()
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 1 Executed "+count+" times");
                Thread.Sleep(1);
            }
        }

        public void testThread2()
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 2 Executed " + count + " times");
                Thread.Sleep(1);
            }
        }
    }
}

After running the application, you should see an output something like below:
Multithreaded programming Example Output

Note that, the output won’t be exact always, it completely depends on how OS provides schedules to CPU for execution of the thread.

Working With ThreadPool:

So, as we have seen so far in above code examples, uses ‘Thread’ in raw mode. However, we can simplify the thread running process with use of ‘ThreadPool’ class that is provided by .NET framework and is very much helpful for quick implementation of multithreaded programming. All we have to do is to queue the function we want running in thread. And it will automatically start executing them. The following code will demonstrate this simplified usage of ‘ThreadPool’ .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new Program().testThread1);
            ThreadPool.QueueUserWorkItem(new Program().testThread2);

            Console.ReadLine();
        }

        public void testThread1(Object threadContext)
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 1 Executed "+count+" times");
                Thread.Sleep(100);
            }
        }

        public void testThread2(Object threadContext)
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 2 Executed " + count + " times");
                Thread.Sleep(100);
            }
        }
    }
}

Further References:

You will may want to look into msdn tutorial on thread and msdn documentation on thread-pool for in-depth overview of the classes. Happy coding :)

Leave a Reply