2012-01-12 14 views
5

我正在使用任務類來執行多線程計算。我可以限制同時運行的System.Threading.Tasks.Task對象的數量嗎?

例如:

List<Task> taskList = new List<Task>(); 
    for(int i=0;i<10;i++){ 
     var task = new Task(() => Console.WriteLine("Hello from taskA.")); 
     taskList.Add(task); 
     task.Start(); 
    } 

有沒有一種方法,使只,比方說,3個任務在大多數運行,其餘的等待?

+5

可能複製http://stackoverflow.com/questions/2898609/system-threading-tasks-limit-the-number-of-concurrent-tasks – Samich 2012-01-12 11:08:39

回答

3

我建議您檢查後here

要進行解釋,請創建相關任務的集合,然後使用ParallelOptions.MaxDegreeOfParallelism來控制同時執行多少個任務。

4

My blog post顯示瞭如何使用任務和動作來做到這一點,並提供了一個示例項目,您可以下載並運行該示例項目以查看兩個實例。

隨着使用操作操作

如果,您可以使用內置的.Net Parallel.Invoke功能。這裏我們限制它並行運行最多3個線程。

var listOfActions = new List<Action>(); 
for (int i = 0; i < 10; i++) 
{ 
    // Note that we create the Action here, but do not start it. 
    listOfActions.Add(() => DoSomething()); 
} 

var options = new ParallelOptions {MaxDegreeOfParallelism = 3}; 
Parallel.Invoke(options, listOfActions.ToArray()); 

隨着任務

由於您使用此任務雖然沒有內置的功能。但是,您可以使用我在我的博客上提供的那個。

/// <summary> 
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. 
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para> 
    /// </summary> 
    /// <param name="tasksToRun">The tasks to run.</param> 
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param> 
    /// <param name="cancellationToken">The cancellation token.</param> 
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken()) 
    { 
     StartAndWaitAllThrottled(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken); 
    } 

    /// <summary> 
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. 
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para> 
    /// </summary> 
    /// <param name="tasksToRun">The tasks to run.</param> 
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param> 
    /// <param name="timeoutInMilliseconds">The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely.</param> 
    /// <param name="cancellationToken">The cancellation token.</param> 
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken()) 
    { 
     // Convert to a list of tasks so that we don&#39;t enumerate over it multiple times needlessly. 
     var tasks = tasksToRun.ToList(); 

     using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel)) 
     { 
      var postTaskTasks = new List<Task>(); 

      // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running. 
      tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release()))); 

      // Start running each task. 
      foreach (var task in tasks) 
      { 
       // Increment the number of tasks currently running and wait if too many are running. 
       throttler.Wait(timeoutInMilliseconds, cancellationToken); 

       cancellationToken.ThrowIfCancellationRequested(); 
       task.Start(); 
      } 

      // Wait for all of the provided tasks to complete. 
      // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler&#39;s using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object. 
      Task.WaitAll(postTaskTasks.ToArray(), cancellationToken); 
     } 
    } 

,然後創建您的任務列表,並調用函數讓他們跑,有說在一次最多3個同時的,你可以這樣做:

var listOfTasks = new List<Task>(); 
for (int i = 0; i < 10; i++) 
{ 
    var count = i; 
    // Note that we create the Task here, but do not start it. 
    listOfTasks.Add(new Task(() => Something())); 
} 
Tasks.StartAndWaitAllThrottled(listOfTasks, 3); 
-1

您可以使用此一個作爲通用

public TaskThrottle(int initialCount, int maxTasksToRunInParallel) 
{ 
    _semaphore = new SemaphoreSlim(initialCount, maxTasksToRunInParallel); 
} 

public void TaskThrottler<T>(IEnumerable<Task<T>> tasks, int timeoutInMilliseconds, CancellationToken cancellationToken = default(CancellationToken)) where T : class 
{ 
     // Get Tasks as List 
     var taskList = tasks as IList<Task<T>> ?? tasks.ToList(); 
     var semaphoreTasks = new List<Task<int>>(); 

     // When the first task completed, flag as done/release 
     taskList.ForEach(x => 
     { 
      semaphoreTasks.Add(x.ContinueWith(y => _semaphore.Release(), cancellationToken)); 
     }); 

     semaphoreTasks.ForEach(async x => 
     { 
      // It will not pass this until one free slot available or timeout occure 
      if(timeoutInMilliseconds > 0) 
       await _semaphore.WaitAsync(timeoutInMilliseconds, cancellationToken); 
      else 
       await _semaphore.WaitAsync(cancellationToken); 

      // Throws a OperationCanceledException if this token has had cancellation requested 
      cancellationToken.ThrowIfCancellationRequested(); 

      // Start the task 
      x.Start(); 
     }); 

     Task.WaitAll(semaphoreTasks.ToArray(), cancellationToken); 
} 
相關問題