Threadpool thread limit

I use ThreadPoolin my application. First I set the thread pool limit using the following:

ThreadPool.SetMaxThreads(m_iThreadPoolLimit,m_iThreadPoolLimit);
m_Events = new ManualResetEvent(false);

and then I queued jobs using the following

WaitCallback objWcb = new WaitCallback(abc);
ThreadPool.QueueUserWorkItem(objWcb, m_objThreadData); 

Here abc is the name of the function that I am calling. After that, I do the following so that all my threads reach 1 point, and the main thread takes over and continues on

m_Events.WaitOne();

My thread limit is 3. The problem that I encountered is a result of limiting the thread pool set to 3, my application processes more than 3 files at a time, while it is assumed that only 3 files are processed at a time. Please help me solve this problem.

+3
source share
4 answers

?

MSDN

/ .

4 , , , - 4.

:

, (IIS) SQL , .

-, IIS, .

+5

Semaphore, 1. , .

var finished = new CountdownEvent(1); // Used to wait for the completion of all work items.
var throttle = new Semaphore(3, 3); // Used to throttle the processing of work items.
foreach (WorkItem item in workitems)
{
  finished.AddCount();
  WorkItem capture = item; // Needed to safely capture the loop variable.
  ThreadPool.QueueUserWorkItem(
    (state) =>
    {
      throttle.WaitOne();
      try
      {
        ProcessWorkItem(capture);
      }
      finally
      {
        throttle.Release();
        finished.Signal();
      }
    }, null);
}
finished.Signal();
finished.Wait();

WorkItem , , .

. Parallel.ForEach ParallelOptions.MaxDegreesOfParallelism, concurrency.

var options = new ParallelOptions();
options.MaxDegreeOfParallelism = 3;
Parallel.ForEach(workitems, options,
  (item) =>
  {
    ProcessWorkItem(item);
  });

1 , ThreadPool Semaphore . . , .

+3

Semaphore .

+1

You say that the files are open: are they actually being actively processed or just stay open? If you leave them open: Have been, did it! Relying on connections and resources (it was a database connection in my case), to close at the end of the scope should work, but it may be required to remove the dispose / garbage command.

0
source

All Articles