My blog post mostra come fare questo sia con le attività e con azioni, e fornisce un progetto di esempio è possibile scaricare ed eseguire di vedere sia in azione.
Con azioni
Se utilizzando azioni, è possibile utilizzare la funzione built-in .Net Parallel.Invoke. Qui lo limitiamo a eseguire al massimo 5 thread in parallelo.
var listOfActions = new List<Action>();
for (int i = 0; i < 100; i++)
{
// Note that we create the Action here, but do not start it.
listOfActions.Add(() => DoSomething());
}
var options = new ParallelOptions {MaxDegreeOfParallelism = 5};
Parallel.Invoke(options, listOfActions.ToArray());
con compiti
Dal momento che si sta utilizzando Task qui però, non v'è alcuna funzione built-in. Tuttavia, puoi utilizzare quello che fornisco sul mio blog.
/// <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'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'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);
}
}
E poi creare l'elenco delle attività e chiamare la funzione di farli correre, con dire un massimo di 5 contemporaneamente alla volta, si potrebbe fare questo:
var listOfTasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
var count = i;
// Note that we create the Task here, but do not start it.
listOfTasks.Add(new Task(() => Something()));
}
Tasks.StartAndWaitAllThrottled(listOfTasks, 5);
Potrebbe illustrare il motivo devi limitarlo alle 5? Si noti che l'utilità di pianificazione non avvierà tutti i 100 allo stesso tempo, utilizza internamente il pool di thread (o il pool di thread utilizza il sistema delle attività) in modo da limitare il numero di attività simultanee a qualcosa di piccolo, ma potrebbe cambiare, e potrebbe essere correlato al numero di core nel tuo sistema, ma sapere perché vuoi limitare a un numero specifico potrebbe dare delle buone risposte. –
Il calcolo chiama effettivamente un webservice come parte della sua operazione. Questo è schiacciante il webservice. 5 è solo un esempio. – James
Che ne dici di Parallel? http://stackoverflow.com/questions/5009181/parallel-foreach-vs-task-factory-startnew – faester