0

I am creating an app that deals with huge number of data to be processed. I want to use threading in C# just to make it processes faster. Please see example code below.

private static void MyProcess(Object someData)
{      
     //Do some data processing       
}

static void Main(string[] args)
{
     for (int task = 1; task < 10; task++)
     {
         ThreadPool.QueueUserWorkItem(new WaitCallback(MyProcess), task);
     }
}

Does this mean that a new thread will be created every loop passing the task to the "MyProcess" method (10 threads total)? Also, are the threads going to process concurrently?

d4zed
  • 478
  • 2
  • 6
  • 16
  • 3
    Why not look at your Threads window while debugging in Visual Studio? – Uwe Keim Sep 03 '19 at 06:59
  • 2
    Since this is your `Main` method (so the process just started), yes the threads are freshly created (the thread pool "caches" these threads in case you want to use them later again). They _may_ run concurrently if you have 10 cpu-cores. – René Vogt Sep 03 '19 at 06:59
  • 2
    `Parallel.For(1, 10, task => { ... })` – Dmitry Bychenko Sep 03 '19 at 07:00

3 Answers3

0

The number of threads a threadpool will start depends on multiple factors, see The managed thread pool

Basically you are queing 10 worker items here which are likely to start threads immediatly.

The threads will most likly run concurrently, depending on the machine and number of processors.

If you start a large number of worker items, they will end up in a queue and start running as soon as a thread becomes available.

Michael Sander
  • 2,677
  • 23
  • 29
0

The calls will be scheduled on the thread pool. It does not guarantee that 10 threads will be created nor that all 10 tasks will be executed concurrently. The number of threads in the thread pool depends on the hardware and is chosen automatically to provide the best performance.

This articles contain good explanations of how it works:

  1. https://owlcation.com/stem/C-ThreadPool-and-its-Task-Queue-Example
  2. https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadpool?redirectedfrom=MSDN&view=netframework-4.8
  3. https://www.c-sharpcorner.com/article/thread-pool-in-net-core-and-c-sharp/

This Stackoverflow question explains the difference between ThreadPool and Thread:
Thread vs ThreadPool

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
0

Your method will be queued 9 times (you start at 1, not 0) for execution and will be executed when a thredpool thread will be available.

d4zed
  • 478
  • 2
  • 6
  • 16