ADVERTISEMENT
ADVERTISEMENT

C# program to create a thread pool

Creating a thread pool in C#: Here, we are going to learn how to create a thread pool in C#?
Submitted by Nidhi, on August 16, 2020

To create a thread pool in the C# program, here we will create different tasks TheadFun1 and ThreadFun2, which is used to print messages on the console using the loop. The ThreadPool class is used to start both tasks without setting any property of threads.

Program:

/*
 * Program to Create Thread Pools in C#
 */
using System;
using System.Threading;

class MyThreadPool
{
    public void ThreadFun1(object obj)
    {
        int loop = 0;
        for (loop = 0; loop <= 4; loop++)
        {
            Console.WriteLine("Thread1 is execting");
        }
    }
    public void ThreadFun2(object obj)
    {
        int loop = 0;
        for (loop = 0; loop <= 4; loop++)
        {
            Console.WriteLine("Thread2 is execting");
        }
    }

    static void Main()
    {
        MyThreadPool TP = new MyThreadPool();

        for (int i = 0; i < 2; i++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(TP.ThreadFun1));
            ThreadPool.QueueUserWorkItem(new WaitCallback(TP.ThreadFun2));
        }
    }
}

Output:

Thread1 is execting
Thread1 is execting
Thread1 is execting
Thread1 is execting
Thread1 is execting
Thread2 is execting
Thread2 is execting
Thread2 is execting
Thread2 is execting
Thread2 is execting
Thread1 is execting
Thread1 is execting
Thread1 is execting
Thread1 is execting
Thread1 is execting
Thread2 is execting
Thread2 is execting
Thread2 is execting
Thread2 is execting
Thread2 is execting
Press any key to continue . . .

Explanation:

In the above program, we created a class MyThreadPool that contains two methods ThreadFun1 and ThreadFun2 to represent tasks. The MyThreadPool class also contains a Main() method to start program execution. Here we created Object TP of MyThreadPool class.

for (int i = 0; i < 2; i++)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback(TP.ThreadFun1));
    ThreadPool.QueueUserWorkItem(new WaitCallback(TP.ThreadFun2));
}

The above code, The WaitCallBack() method is used to point the method to execute thread from the pool of thread.

C# Thread Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.