user3651810
user3651810

Reputation: 129

Multithreaded code to do work using configured number of thread

I want to create a multithreaded application code. I want to execute configured no of threads and each thread do the work. I want to know is this the write approach or do we have better approach. All the threads needs to be executed asynchronously.

    public static bool keepThreadsAlive = false;
    static void Main(string[] args)
    {
        Program pgm = new Program();
        int noOfThreads = 4;
        keepThreadsAlive = true;
        for (int i = 1; i <= noOfThreads; i++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)i);
        }

        System.Console.ReadLine();
        StopAllThreads();
        System.Console.ReadLine();
    }

    private static void DoWork(object threadNumber)
    { 
        int threadNum = (int)threadNumber;
        int counter = 1;
        while (keepThreadsAlive)
        {
            counter = ProcessACK(threadNum, counter);
        }
    }

    private static int ProcessACK(int threadNum, int counter)
    {
        System.Console.WriteLine("Thread {0} count {1}", threadNum, counter++);
        Random ran = new Random();
        int randomNumber = ran.Next(5000, 100000);
        for (int i = 0; i < randomNumber; i++) ;
        Thread.Sleep(2000);
        return counter;
    }

Upvotes: 1

Views: 43

Answers (1)

Matt Cashatt
Matt Cashatt

Reputation: 24228

As others have pointed out, the methods you are using are dated and not as elegant as the more modern C# approach to accomplishing the same tasks.

Have a look at System.Threading.Tasks for an overview of what is available to you these days. There is even a way to set the maximum threads used in a parallel operation. Here is a simple (pseudocode) example:

Parallel.ForEach(someListOfItems, new ParallelOptions { MaxDegreeOfParallelism = 8 }, item =>
  {
      //do stuff for each item in "someListOfItems" using a maximum of 8 threads.
  });

Hope this helps.

Upvotes: 1

Related Questions