C# Threading Example

In this tutorial, we will learn threading, multithreading, threadpool, thread join in C#.

In this post I will cover following aspects of threading, which I feel is basic you must know, threading is huge, many aspects to play with!

To create thread in .Net Framework, we need to use System.Threading namespace, all thread-associated classes are under System.Threading namespace

Just think, when we need threading in development! When we have some long time taking task to be completed, and at the same time user should be able to perform other task without being interrupted, in that situation we use threading.

If you are not familiar with using Task then I would say please look at C# Task tutorial with example, that will help you to understand Threading better.

Threading in C#

Here is an example of how to create a new Thread.

using System;                  
using System.Threading;     
  
Thread t1 = new Thread();            

Here we write a function for some long time taking task, that will Fetch 100000 records from database and send customized email to each user.

class ThreadingSample
{
    public static void MyLongTask1()
    {
        List<object> objCollection = null; 
             
        foreach (object o in objCollection)
        {           
        // here we can do any database task or sending email.
        // fetching 100000 records from database and send them customized email
        System.Console.WriteLine("Processing... my thread running");
        }
    }
}

We need to put the above log task in a thread, so our GUI remains free for user to perform other activities.

void ProcessNow()
{
    Thread MyThread = new Thread(new ThreadStart(MyLongTask1));

    MyThread.Start();
}
C# ThreadPool Example

A collection of configured Threads ready to serve incoming asynchronous task is called "ThreadPool". ThreadPool manages a group of threads, ThreadPool technique improves the responsiveness of the application.

Once a thread completes its task, it sent to the pool to a queue of waiting threads, where it can be reused. Reusability of same thread avoids any application to create more threads and helps in less memory consumption.

using System.Threading;
using System.Diagnostics;

ThreadPool.QueueUserWorkItem(new WaitCallback(Process));

Here is an example of how you can create ThreadPool using ThreadPool.QueueUserWorkItem.

// call (1)
ThreadPool.QueueUserWorkItem(a => Method1(4, "my param 1"));

// call (2)
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate (object state)
{ Method1(6, "my param 10"); }), null);

In above thread pool example I have called a void Method1 with two parameters, you can call your void method from there, ideally that should be any long task method that you want to add in thread pool.

static void Method1(int number, string message)
{
for (int i = 0; i <= number; i++)
    {
        TotalScore = TotalScore + i;
    }
    Console.WriteLine($"{message}, TotalScore {TotalScore}");
}

After adding in thread pool you may be interested to know how many thread are running at that moment, here is how you can get current thread count.

int max, max2;
ThreadPool.GetMaxThreads(out max, out max2);

int available, available2;
ThreadPool.GetAvailableThreads(out available, out available2);

int runningThread = max - available;
Console.WriteLine($"running therads count: {runningThread}");

If you want to know the total thread count of the current process, use following code.

int threadCount = Process.GetCurrentProcess().Threads.Count;
Console.WriteLine($"threadCount-{threadCount}");
Thread.Join Example

thread join() method is used blocks the current thread, and makes it wait until its all child threads to finish their task.

Join method also has overload where we can specify the timeout in milliseconds.

If we don’t use join() method in main() thread, then the main thread may die before child thread

class MethodUtil
{
    public void LongFunction1()
    {
        Console.WriteLine("LongFunction1 started");
        Thread.Sleep(5000);
        Console.WriteLine("LongFunction1 complete");
    }

    public void LongFunction2()
    {
        Console.WriteLine("LongFunction2 started");
        Thread.Sleep(5000);
        Console.WriteLine("LongFunction2 complete");
    }
}

Here is a quick small piece of code to understand how thread joins works.

MethodUtil util = new MethodUtil();
Thread t1 = new Thread(new ThreadStart(util.LongFunction1));
t1.Start();
Thread t2 = new Thread(new ThreadStart(util.LongFunction2));
t2.Start();
t1.Join();
t2.Join();
for (int i = 1; i <= 10; i++)
{
    if (t1.IsAlive)
    {
        Console.WriteLine("LongFunction1 working");
        Thread.Sleep(500);
    }
    else
    {
        Console.WriteLine("LongFunction1 Completed");
        break;
    }
}
Console.WriteLine("Main Thread Completed");
Console.ReadLine();
C# Multithreading Example

Multithreading is basically creating multiple threads; where all above threading principal remain same. However, while creating multiple thread, we need to be more cautious about each thread process and result, should consider all possibilities like what if thread takes more than expected time, what are the dependency factors, what if tread is stuck, what would be the impact on other threads etc.

MethodUtil util = new MethodUtil();
Thread t1 = new Thread(new ThreadStart(util.LongFunction1));
t1.Start();
Thread t2 = new Thread(new ThreadStart(util.LongFunction2));
t2.Start();

Here are few useful thread handling functions.

  • Abort()

    Stop the execution of the thread permanently.

  • Suspend()

    Pauses the execution of the thread temporarily, if already suspended then nothing will happen.

  • Resume()

    Resumes the execution of a suspended thread.

  • IsAlive

    IsAlive is a Boolean property, which indicates if the thread is still running.

Please feel free to ask more threading question, we will try to update this post with answer of your query.

You should also look at following tutorials

 
Threading in C#
in C# Tutorials
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course