Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
TaskList.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Collections.Generic;
5 using System.Threading.Tasks;
6 
7 namespace SiliconStudio.Paradox.Threading
8 {
9  /// <summary>
10  /// Helper methods to dispatch action-items from a list to several threads.
11  /// </summary>
12  public sealed class TaskList
13  {
14  /// <summary>
15  /// Dispatcher to process items on several threads with a specified action.
16  /// </summary>
17  /// <typeparam name="T">Type of the item data.</typeparam>
18  /// <param name="items">The items.</param>
19  /// <param name="threadCount">The thread count, number of thread tasks in parallel.</param>
20  /// <param name="threshold">The threshold, if number of items is above the threshold, the task parallel is used, otherwise it is sequential.</param>
21  /// <param name="action">The action.</param>
22  public static void Dispatch<T>(IList<T> items, int threadCount, int threshold, Action<int, T> action)
23  {
24  if (items.Count < threshold)
25  {
26  for (int i = 0; i < items.Count; i++)
27  {
28  var entity = items[i];
29  action(i, entity);
30  }
31  }
32  else
33  {
34  var count = items.Count / threadCount;
35 
36  var tasks = new Task[threadCount];
37 
38  int fromIndex = 0;
39  for (int i = 0; i < threadCount; i++)
40  {
41  if ((i + 1) == threadCount)
42  {
43  count += items.Count - count * threadCount;
44  }
45 
46  var localIndex = fromIndex;
47  var localCount = count;
48  var task = new Task(
49  () =>
50  {
51  for (int j = 0; j < localCount; j++)
52  {
53  var entity = items[j + localIndex];
54  action(j + localIndex, entity);
55  }
56  });
57  tasks[i] = task;
58  task.Start();
59  fromIndex += count;
60  }
61 
62  Task.WaitAll(tasks);
63  }
64  }
65  }
66 }
_In_ size_t _In_ DXGI_FORMAT _In_ size_t _In_ float threshold
Definition: DirectXTexP.h:183
System.Threading.Tasks.Task Task
_In_ size_t count
Definition: DirectXTexP.h:174
Helper methods to dispatch action-items from a list to several threads.
Definition: TaskList.cs:12