C# Program to Create Thread Pools
Posted by Superadmin on August 11 2022 09:36:19

C# Program to Create Thread Pools

 

This is a C# Program to create thread pools.

Problem Description

This C# Program Creates Thread Pools.

Problem Solution

Here it comprises two separate tasks called Task1 and Task2 that do the simple job of outputting a message to the console in a loop. A ThreadPool class can be employed to start these two tasks without setting the properties of threads.

Program/Source Code

Here is source code of the C# Program to Create Thread Pools. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Create Thread Pools
 */
using System;
using System.Threading;
class ThreadPoolDemo
{
    public void task1(object obj)
    {
        for (int i = 0; i <= 2; i++)
        {
            Console.WriteLine("Task 1 is being executed");
        }
    }
    public void task2(object obj)
    {
        for (int i = 0; i <= 2; i++)
        {
            Console.WriteLine("Task 2 is being executed");
        }
    }
 
    static void Main()
    {
        ThreadPoolDemo tpd = new ThreadPoolDemo();
        for (int i = 0; i < 2; i++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.task1));
            ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.task2));
        }
 
        Console.Read();
    }
}
Program Explanation

In this C# program, here it comprises two separate tasks called Task1 and Task2 that do the simple job of outputting a message to the console in a loop. A ThreadPool class can be employed to start these two tasks without setting the properties of threads.

The WaitCallback() method in this case represents a pointer to a function that will be executed on a thread from the thread pool, if no thread is available it will wait until one gets freed.

Runtime Test Cases
 
Task 1 is being executed
Task 1 is being executed
Task 1 is being executed
Task 1 is being executed
Task 1 is being executed
Task 1 is being executed
Task 2 is being executed
Task 2 is being executed
Task 2 is being executed
Task 2 is being executed
Task 2 is being executed
Task 2 is being executed