Parallel.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. // Parallel.cs
  2. //
  3. // Copyright (c) 2008 Jérémie "Garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. #if NET_4_0
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Collections.Concurrent;
  28. using System.Threading;
  29. namespace System.Threading.Tasks
  30. {
  31. public static class Parallel
  32. {
  33. internal static int GetBestWorkerNumber ()
  34. {
  35. return GetBestWorkerNumber (TaskScheduler.Current);
  36. }
  37. internal static int GetBestWorkerNumber (TaskScheduler scheduler)
  38. {
  39. return scheduler.MaximumConcurrencyLevel;
  40. }
  41. static int GetBestWorkerNumber (int from, int to, ParallelOptions options, out int step)
  42. {
  43. int num = Math.Min (GetBestWorkerNumber (),
  44. options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
  45. // Integer range that each task process
  46. if ((step = (to - from) / num) < 5) {
  47. step = 5;
  48. num = (to - from) / 5;
  49. if (num < 1)
  50. num = 1;
  51. }
  52. return num;
  53. }
  54. static void HandleExceptions (IEnumerable<Task> tasks)
  55. {
  56. HandleExceptions (tasks, null);
  57. }
  58. static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
  59. {
  60. List<Exception> exs = new List<Exception> ();
  61. foreach (Task t in tasks) {
  62. if (t.Exception != null)
  63. exs.Add (t.Exception);
  64. }
  65. if (exs.Count > 0) {
  66. if (infos != null)
  67. infos.IsExceptional = true;
  68. throw new AggregateException (exs);
  69. }
  70. }
  71. static void InitTasks (Task[] tasks, int count, Action action, ParallelOptions options)
  72. {
  73. TaskCreationOptions creation = TaskCreationOptions.LongRunning;
  74. for (int i = 0; i < count; i++) {
  75. if (options == null)
  76. tasks [i] = Task.Factory.StartNew (action, creation);
  77. else
  78. tasks [i] = Task.Factory.StartNew (action, options.CancellationToken, creation, options.TaskScheduler);
  79. }
  80. }
  81. #region For
  82. public static ParallelLoopResult For (int from, int to, Action<int> action)
  83. {
  84. return For (from, to, ParallelOptions.Default, action);
  85. }
  86. public static ParallelLoopResult For (int from, int to, Action<int, ParallelLoopState> action)
  87. {
  88. return For (from, to, ParallelOptions.Default, action);
  89. }
  90. public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int> action)
  91. {
  92. return For (from, to, options, (index, state) => action (index));
  93. }
  94. public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int, ParallelLoopState> action)
  95. {
  96. return For<object> (from, to, options, () => null, (i, s, l) => { action (i, s); return null; }, _ => {});
  97. }
  98. public static ParallelLoopResult For<TLocal> (int from,
  99. int to,
  100. Func<TLocal> init,
  101. Func<int, ParallelLoopState, TLocal, TLocal> action,
  102. Action<TLocal> destruct)
  103. {
  104. return For<TLocal> (from, to, ParallelOptions.Default, init, action, destruct);
  105. }
  106. public static ParallelLoopResult For<TLocal> (int from,
  107. int to,
  108. ParallelOptions options,
  109. Func<TLocal> init,
  110. Func<int, ParallelLoopState, TLocal, TLocal> action,
  111. Action<TLocal> destruct)
  112. {
  113. if (action == null)
  114. throw new ArgumentNullException ("action");
  115. if (init == null)
  116. throw new ArgumentNullException ("localInit");
  117. if (destruct == null)
  118. throw new ArgumentNullException ("localFinally");
  119. if (options == null)
  120. throw new ArgumentNullException ("options");
  121. if (from >= to)
  122. return new ParallelLoopResult (null, true);
  123. // Number of task to be launched (normally == Env.ProcessorCount)
  124. int step;
  125. int num = GetBestWorkerNumber (from, to, options, out step);
  126. Task[] tasks = new Task [num];
  127. StealRange[] ranges = new StealRange[num];
  128. for (int i = 0; i < num; i++)
  129. ranges[i] = new StealRange (from, i, step);
  130. ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
  131. int currentIndex = -1;
  132. Action workerMethod = delegate {
  133. int localWorker = Interlocked.Increment (ref currentIndex);
  134. StealRange range = ranges[localWorker];
  135. int index = range.Actual;
  136. int stopIndex = localWorker + 1 == num ? to : Math.Min (to, index + step);
  137. TLocal local = init ();
  138. ParallelLoopState state = new ParallelLoopState (infos);
  139. CancellationToken token = options.CancellationToken;
  140. try {
  141. for (int i = index; i < stopIndex; range.Actual = ++i) {
  142. if (infos.IsStopped)
  143. return;
  144. token.ThrowIfCancellationRequested ();
  145. if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
  146. return;
  147. state.CurrentIteration = i;
  148. local = action (i, state, local);
  149. if (i >= stopIndex - range.Stolen)
  150. break;
  151. }
  152. // Try to steal from our right neighbor (cyclic)
  153. int len = num + localWorker;
  154. for (int sIndex = localWorker + 1; sIndex < len; ++sIndex) {
  155. int extWorker = sIndex % num;
  156. range = ranges[extWorker];
  157. stopIndex = extWorker + 1 == num ? to : Math.Min (to, from + (extWorker + 1) * step);
  158. int stolen;
  159. do {
  160. stolen = range.Stolen;
  161. if (stopIndex - stolen > range.Actual)
  162. goto next;
  163. } while (Interlocked.CompareExchange (ref range.Stolen, stolen + 1, stolen) != stolen);
  164. stolen = stopIndex - stolen - 1;
  165. if (stolen > range.Actual)
  166. local = action (stolen, state, local);
  167. next:
  168. continue;
  169. }
  170. } finally {
  171. destruct (local);
  172. }
  173. };
  174. InitTasks (tasks, num, workerMethod, options);
  175. try {
  176. Task.WaitAll (tasks);
  177. } catch {
  178. HandleExceptions (tasks, infos);
  179. }
  180. return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
  181. }
  182. class StealRange
  183. {
  184. public int Stolen;
  185. public int Actual;
  186. public StealRange (int from, int i, int step)
  187. {
  188. Actual = from + i * step;
  189. }
  190. }
  191. #endregion
  192. #region Foreach
  193. static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
  194. Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
  195. Action<TLocal> destruct)
  196. {
  197. if (enumerable == null)
  198. throw new ArgumentNullException ("source");
  199. if (options == null)
  200. throw new ArgumentNullException ("options");
  201. if (action == null)
  202. throw new ArgumentNullException ("action");
  203. if (init == null)
  204. throw new ArgumentNullException ("init");
  205. if (destruct == null)
  206. throw new ArgumentNullException ("destruct");
  207. int num = Math.Min (GetBestWorkerNumber (),
  208. options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
  209. Task[] tasks = new Task[num];
  210. ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
  211. SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
  212. const int bagCount = 5;
  213. IList<IEnumerator<TSource>> slices = enumerable (num);
  214. int sliceIndex = 0;
  215. Func<ParallelLoopState, bool> cancellationTokenTest = (s) => {
  216. if (options != null && options.CancellationToken.IsCancellationRequested) {
  217. s.Stop ();
  218. return true;
  219. }
  220. return false;
  221. };
  222. Action workerMethod = delegate {
  223. IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex) - 1];
  224. TLocal local = (init != null) ? init () : default (TLocal);
  225. ParallelLoopState state = new ParallelLoopState (infos);
  226. int workIndex = bag.GetNextIndex ();
  227. try {
  228. bool cont = true;
  229. TSource element;
  230. while (cont) {
  231. if (infos.IsStopped)
  232. return;
  233. if (cancellationTokenTest (state))
  234. return;
  235. for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
  236. bag.Add (workIndex, slice.Current);
  237. }
  238. for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
  239. if (infos.IsStopped)
  240. return;
  241. if (cancellationTokenTest (state))
  242. return;
  243. local = action (element, state, local);
  244. }
  245. }
  246. while (bag.TrySteal (workIndex, out element)) {
  247. if (infos.IsStopped)
  248. return;
  249. if (cancellationTokenTest (state))
  250. return;
  251. local = action (element, state, local);
  252. }
  253. } finally {
  254. if (destruct != null)
  255. destruct (local);
  256. }
  257. };
  258. InitTasks (tasks, num, workerMethod, options);
  259. try {
  260. Task.WaitAll (tasks);
  261. } catch {
  262. HandleExceptions (tasks, infos);
  263. }
  264. return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
  265. }
  266. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource> action)
  267. {
  268. if (enumerable == null)
  269. throw new ArgumentNullException ("source");
  270. if (action == null)
  271. throw new ArgumentNullException ("action");
  272. return ForEach<TSource, object> (Partitioner.Create (enumerable),
  273. ParallelOptions.Default,
  274. () => null,
  275. (e, s, l) => { action (e); return null; },
  276. _ => {});
  277. }
  278. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource, ParallelLoopState> action)
  279. {
  280. if (enumerable == null)
  281. throw new ArgumentNullException ("source");
  282. if (action == null)
  283. throw new ArgumentNullException ("action");
  284. return ForEach<TSource, object> (Partitioner.Create (enumerable),
  285. ParallelOptions.Default,
  286. () => null,
  287. (e, s, l) => { action (e, s); return null; },
  288. _ => {});
  289. }
  290. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable,
  291. Action<TSource, ParallelLoopState, long> action)
  292. {
  293. if (enumerable == null)
  294. throw new ArgumentNullException ("source");
  295. if (action == null)
  296. throw new ArgumentNullException ("action");
  297. return ForEach<TSource, object> (Partitioner.Create (enumerable),
  298. ParallelOptions.Default,
  299. () => null,
  300. (e, s, l) => { action (e, s, -1); return null; },
  301. _ => {});
  302. }
  303. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
  304. Action<TSource, ParallelLoopState> body)
  305. {
  306. if (body == null)
  307. throw new ArgumentNullException ("body");
  308. return ForEach<TSource, object> (source,
  309. ParallelOptions.Default,
  310. () => null,
  311. (e, s, l) => { body (e, s); return null; },
  312. _ => {});
  313. }
  314. public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
  315. Action<TSource, ParallelLoopState, long> body)
  316. {
  317. if (body == null)
  318. throw new ArgumentNullException ("body");
  319. return ForEach<TSource, object> (source,
  320. ParallelOptions.Default,
  321. () => null,
  322. (e, s, i, l) => { body (e, s, i); return null; },
  323. _ => {});
  324. }
  325. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
  326. Action<TSource> body)
  327. {
  328. if (body == null)
  329. throw new ArgumentNullException ("body");
  330. return ForEach<TSource, object> (source,
  331. ParallelOptions.Default,
  332. () => null,
  333. (e, s, l) => { body (e); return null; },
  334. _ => {});
  335. }
  336. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
  337. ParallelOptions parallelOptions,
  338. Action<TSource> body)
  339. {
  340. if (source == null)
  341. throw new ArgumentNullException ("source");
  342. if (body == null)
  343. throw new ArgumentNullException ("body");
  344. return ForEach<TSource, object> (Partitioner.Create (source),
  345. parallelOptions,
  346. () => null,
  347. (e, s, l) => { body (e); return null; },
  348. _ => {});
  349. }
  350. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  351. Action<TSource, ParallelLoopState> body)
  352. {
  353. if (source == null)
  354. throw new ArgumentNullException ("source");
  355. if (body == null)
  356. throw new ArgumentNullException ("body");
  357. return ForEach<TSource, object> (Partitioner.Create (source),
  358. parallelOptions,
  359. () => null,
  360. (e, s, l) => { body (e, s); return null; },
  361. _ => {});
  362. }
  363. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  364. Action<TSource, ParallelLoopState, long> body)
  365. {
  366. if (source == null)
  367. throw new ArgumentNullException ("source");
  368. if (body == null)
  369. throw new ArgumentNullException ("body");
  370. return ForEach<TSource, object> (Partitioner.Create (source),
  371. parallelOptions,
  372. () => null,
  373. (e, s, i, l) => { body (e, s, i); return null; },
  374. _ => {});
  375. }
  376. public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
  377. Action<TSource, ParallelLoopState, long> body)
  378. {
  379. if (body == null)
  380. throw new ArgumentNullException ("body");
  381. return ForEach<TSource, object> (source,
  382. parallelOptions,
  383. () => null,
  384. (e, s, i, l) => { body (e, s, i); return null; },
  385. _ => {});
  386. }
  387. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
  388. Action<TSource> body)
  389. {
  390. if (body == null)
  391. throw new ArgumentNullException ("body");
  392. return ForEach<TSource, object> (source,
  393. parallelOptions,
  394. () => null,
  395. (e, s, l) => { body (e); return null; },
  396. _ => {});
  397. }
  398. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
  399. Action<TSource, ParallelLoopState> body)
  400. {
  401. return ForEach<TSource, object> (source,
  402. parallelOptions,
  403. () => null,
  404. (e, s, l) => { body (e, s); return null; },
  405. _ => {});
  406. }
  407. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
  408. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  409. Action<TLocal> localFinally)
  410. {
  411. if (source == null)
  412. throw new ArgumentNullException ("source");
  413. return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source),
  414. ParallelOptions.Default,
  415. localInit,
  416. body,
  417. localFinally);
  418. }
  419. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
  420. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  421. Action<TLocal> localFinally)
  422. {
  423. return ForEach<TSource, TLocal> (Partitioner.Create (source),
  424. ParallelOptions.Default,
  425. localInit,
  426. body,
  427. localFinally);
  428. }
  429. public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
  430. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  431. Action<TLocal> localFinally)
  432. {
  433. return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
  434. }
  435. public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
  436. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  437. Action<TLocal> localFinally)
  438. {
  439. return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
  440. }
  441. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  442. Func<TLocal> localInit,
  443. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  444. Action<TLocal> localFinally)
  445. {
  446. if (source == null)
  447. throw new ArgumentNullException ("source");
  448. return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
  449. }
  450. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  451. Func<TLocal> localInit,
  452. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  453. Action<TLocal> localFinally)
  454. {
  455. if (source == null)
  456. throw new ArgumentNullException ("source");
  457. return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
  458. }
  459. public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> enumerable, ParallelOptions options,
  460. Func<TLocal> init,
  461. Func<TSource, ParallelLoopState, TLocal, TLocal> action,
  462. Action<TLocal> destruct)
  463. {
  464. if (enumerable == null)
  465. throw new ArgumentNullException ("source");
  466. if (action == null)
  467. throw new ArgumentNullException ("action");
  468. return ForEach<TSource, TLocal> (enumerable.GetPartitions, options, init, action, destruct);
  469. }
  470. public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> enumerable, ParallelOptions options,
  471. Func<TLocal> init,
  472. Func<TSource, ParallelLoopState, long, TLocal, TLocal> action,
  473. Action<TLocal> destruct)
  474. {
  475. if (enumerable == null)
  476. throw new ArgumentNullException ("source");
  477. if (action == null)
  478. throw new ArgumentNullException ("action");
  479. return ForEach<KeyValuePair<long, TSource>, TLocal> (enumerable.GetOrderablePartitions,
  480. options,
  481. init,
  482. (e, s, l) => action (e.Value, s, e.Key, l),
  483. destruct);
  484. }
  485. #endregion
  486. #region Invoke
  487. public static void Invoke (params Action[] actions)
  488. {
  489. if (actions == null)
  490. throw new ArgumentNullException ("actions");
  491. Invoke (actions, (Action a) => Task.Factory.StartNew (a));
  492. }
  493. public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
  494. {
  495. if (parallelOptions == null)
  496. throw new ArgumentNullException ("parallelOptions");
  497. if (actions == null)
  498. throw new ArgumentNullException ("actions");
  499. Invoke (actions, (Action a) => Task.Factory.StartNew (a, parallelOptions.CancellationToken, TaskCreationOptions.None, parallelOptions.TaskScheduler));
  500. }
  501. static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
  502. {
  503. if (actions.Length == 0)
  504. throw new ArgumentException ("actions is empty");
  505. // Execute it directly
  506. if (actions.Length == 1 && actions[0] != null)
  507. actions[0] ();
  508. bool shouldThrow = false;
  509. Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
  510. if (a == null) {
  511. shouldThrow = true;
  512. return null;
  513. }
  514. return taskCreator (a);
  515. });
  516. if (shouldThrow)
  517. throw new ArgumentException ("One action in actions is null", "actions");
  518. try {
  519. Task.WaitAll (ts);
  520. } catch {
  521. HandleExceptions (ts);
  522. }
  523. }
  524. #endregion
  525. #region SpawnBestNumber, used by PLinq
  526. internal static Task[] SpawnBestNumber (Action action, Action callback)
  527. {
  528. return SpawnBestNumber (action, -1, callback);
  529. }
  530. internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
  531. {
  532. return SpawnBestNumber (action, dop, false, callback);
  533. }
  534. internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
  535. {
  536. // Get the optimum amount of worker to create
  537. int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
  538. // Initialize worker
  539. CountdownEvent evt = new CountdownEvent (num);
  540. Task[] tasks = new Task [num];
  541. for (int i = 0; i < num; i++) {
  542. tasks [i] = Task.Factory.StartNew (() => {
  543. action ();
  544. evt.Signal ();
  545. if (callback != null && evt.IsSet)
  546. callback ();
  547. });
  548. }
  549. // If explicitely told, wait for all workers to complete
  550. // and thus let main thread participate in the processing
  551. if (wait)
  552. Task.WaitAll (tasks);
  553. return tasks;
  554. }
  555. #endregion
  556. }
  557. }
  558. #endif