- ThreadPool frustrations - Thread creation exceeding SetMaxThreads
- ThreadPool.SetMaxThreads(5, 0);
- List<task> tasks = GetTasks();
- int toProcess = tasks.Count;
- ManualResetEvent resetEvent = new ManualResetEvent(false);
- for (int i = 0; i < tasks.Count; i++)
- {
- ReportGenerator worker = new ReportGenerator(tasks[i].Code, id);
- ThreadPool.QueueUserWorkItem(x =>
- {
- worker.Go();
- if (Interlocked.Decrement(ref toProcess) == 0)
- resetEvent.Set();
- });
- }
- resetEvent.WaitOne();
- List<task> tasks = GetTasks();
- Parallel.ForEach(tasks, new ParallelOptions { MaxDegreeOfParallelism = 5 },
- task => {ReportGenerator worker = new ReportGenerator(task.Code, id);
- worker.Go();});
- // New variable in your class definition
- private int taskStackPointer;
- private final static int MAX_THREADS = 5;
- // Make sure that only one thread has access at a time
- [MethodImpl(MethodImplOptions.Synchronized)]
- public task getNextTask()
- {
- if( taskStackPointer < tasks.Count )
- return tasks[taskStackPointer++];
- else
- return null;
- }
- public interface TaskDispatcher
- {
- [MethodImpl(MethodImplOptions.Synchronized)] public task getNextTask();
- }
- public ReportGenerator( TaskDispatcher td, int idCode )
- {
- ...
- }
- taskStackPointer = 0;
- for (int i = 0; i < MAX_THREADS; i++)
- {
- ReportGenerator worker = new ReportGenerator(this,id);
- worker.Go();
- }
- List<task> tasks = GetTasks();
- var parallelOptions = new ParallelOptions
- {
- MaxDegreeOfParallelism = 5
- };
- Parallel.ForEach(collection.GetConsumingEnumerable(), options, x =>
- {
- // Do work here...
- });