code_junkie

Speed up loop using multithreading in C# (Question)

Nov 11th, 2011
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. foreach (String item in ListOfStrings)
  2. {
  3. result.add(CalculateSmth(item));
  4. }
  5.  
  6. Parallel.Foreach (ListOfStrings, (item) =>
  7. result.add(CalculateSmth(item));
  8. );
  9.  
  10. using System.Collections.Generic;
  11. using System.Threading;
  12.  
  13. namespace noocyte.Threading
  14. {
  15. class CalcState
  16. {
  17. public CalcState(ManualResetEvent reset, string input) {
  18. Reset = reset;
  19. Input = input;
  20. }
  21. public ManualResetEvent Reset { get; private set; }
  22. public string Input { get; set; }
  23. }
  24.  
  25. class CalculateMT
  26. {
  27. List<string> result = new List<string>();
  28. List<ManualResetEvent> events = new List<ManualResetEvent>();
  29.  
  30. private void Calc() {
  31. List<string> aList = new List<string>();
  32. aList.Add("test");
  33.  
  34. foreach (var item in aList)
  35. {
  36. CalcState cs = new CalcState(new ManualResetEvent(false), item);
  37. events.Add(cs.Reset);
  38. ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), cs);
  39. }
  40. WaitHandle.WaitAll(events.ToArray());
  41. }
  42.  
  43. private void Calculate(object s)
  44. {
  45. CalcState cs = s as CalcState;
  46. cs.Reset.Set();
  47. result.Add(cs.Input);
  48. }
  49. }
  50. }
  51.  
  52. List<string> work = (some list with lots of strings)
  53.  
  54. // Split the work in two
  55. List<string> odd = new List<string>();
  56. List<string> even = new List<string>();
  57. for (int i = 0; i < work.Count; i++)
  58. {
  59. if (i % 2 == 0)
  60. {
  61. even.Add(work[i]);
  62. }
  63. else
  64. {
  65. odd.Add(work[i]);
  66. }
  67. }
  68.  
  69. // Set up to worker delegates
  70. List<Foo> oddResult = new List<Foo>();
  71. Action oddWork = delegate { foreach (string item in odd) oddResult.Add(CalculateSmth(item)); };
  72.  
  73. List<Foo> evenResult = new List<Foo>();
  74. Action evenWork = delegate { foreach (string item in even) evenResult.Add(CalculateSmth(item)); };
  75.  
  76. // Run two delegates asynchronously
  77. IAsyncResult evenHandle = evenWork.BeginInvoke(null, null);
  78. IAsyncResult oddHandle = oddWork.BeginInvoke(null, null);
  79.  
  80. // Wait for both to finish
  81. evenWork.EndInvoke(evenHandle);
  82. oddWork.EndInvoke(oddHandle);
  83.  
  84. // Merge the results from the two jobs
  85. List<Foo> allResults = new List<Foo>();
  86. allResults.AddRange(oddResult);
  87. allResults.AddRange(evenResult);
  88.  
  89. return allResults;
Add Comment
Please, Sign In to add comment