Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.72 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. ThreadPool frustrations - Thread creation exceeding SetMaxThreads
  2. ThreadPool.SetMaxThreads(5, 0);
  3.  
  4.         List<task> tasks = GetTasks();
  5.  
  6.         int toProcess = tasks.Count;
  7.         ManualResetEvent resetEvent = new ManualResetEvent(false);
  8.  
  9.         for (int i = 0; i < tasks.Count; i++)
  10.         {
  11.             ReportGenerator worker = new ReportGenerator(tasks[i].Code, id);
  12.             ThreadPool.QueueUserWorkItem(x =>
  13.             {
  14.                 worker.Go();
  15.                 if (Interlocked.Decrement(ref toProcess) == 0)
  16.                     resetEvent.Set();
  17.             });
  18.         }
  19.  
  20.         resetEvent.WaitOne();
  21.        
  22. List<task> tasks = GetTasks();
  23.  
  24. Parallel.ForEach(tasks, new ParallelOptions { MaxDegreeOfParallelism = 5 },
  25.   task => {ReportGenerator worker = new ReportGenerator(task.Code, id);
  26.            worker.Go();});
  27.        
  28. // New variable in your class definition
  29. private int taskStackPointer;
  30. private final static int MAX_THREADS = 5;
  31.        
  32. // Make sure that only one thread has access at a time
  33. [MethodImpl(MethodImplOptions.Synchronized)]
  34. public task getNextTask()
  35. {
  36.     if( taskStackPointer < tasks.Count )
  37.         return tasks[taskStackPointer++];
  38.     else
  39.         return null;
  40. }
  41.        
  42. public interface TaskDispatcher
  43. {
  44.      [MethodImpl(MethodImplOptions.Synchronized)] public task getNextTask();
  45. }
  46.        
  47. public ReportGenerator( TaskDispatcher td, int idCode )
  48. {
  49.     ...
  50. }
  51.        
  52. taskStackPointer = 0;
  53. for (int i = 0; i < MAX_THREADS; i++)
  54. {
  55.     ReportGenerator worker = new ReportGenerator(this,id);
  56.     worker.Go();
  57. }
  58.        
  59. List<task> tasks = GetTasks();
  60.        
  61. var parallelOptions = new ParallelOptions
  62. {
  63.     MaxDegreeOfParallelism = 5
  64. };
  65.  
  66. Parallel.ForEach(collection.GetConsumingEnumerable(), options, x =>
  67. {
  68.     // Do work here...
  69. });