yüklemek her dosya için bir Eylem veya Görev oluşturmak istiyorum gidiyoruz: sevdiği döngü şey Ardından
ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 4;
Onları bir Liste'ye koyun ve ardından bu listeyi paralel olarak işlenebilecek sayıyı sınırlandırarak işleyin.
My blog post hem Görevler hem de Eylemler ile bunun nasıl yapıldığını gösterir ve her ikisini de görebilmek için indirip çalıştırabileceğiniz bir örnek proje sağlar. Eylemler kullanarak Eylemler
Şunla
, yerleşik .Net Parallel.Invoke işlevini kullanabilirsiniz. Burada paralel olarak en fazla 4 iplik ile çalışmasını sınırlandırıyoruz.
var listOfActions = new List<Action>();
foreach (var file in files)
{
var localFile = file;
// Note that we create the Task here, but do not start it.
listOfTasks.Add(new Task(() => UploadFile(localFile)));
}
var options = new ParallelOptions {MaxDegreeOfParallelism = 4};
Parallel.Invoke(options, listOfActions.ToArray());
Bu seçenek olsa asenk desteklemez ve aşağıdaki Görev örneği kullanmak isteyebilirsiniz yüzden, sen FileUpload fonksiyonu olacaktır farzederek söylüyorum. Görevler ile Görevler
ile
yerleşik bir işlevi yoktur. Ancak, blogumda sağladığımı kullanabilirsiniz.Ayrıca
var listOfTasks = new List<Task>();
foreach (var file in files)
{
var localFile = file;
// Note that we create the Task here, but do not start it.
listOfTasks.Add(new Task(async() => await UploadFile(localFile)));
}
await Tasks.StartAndWaitAllThrottledAsync(listOfTasks, 4);
bu çünkü:
/// <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 async Task StartAndWaitAllThrottledAsync(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken())
{
await StartAndWaitAllThrottledAsync(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken);
}
/// <summary>
/// Starts the given tasks and waits for them to complete. This will run the specified number of tasks in parallel.
/// <para>NOTE: If a timeout is reached before the Task completes, another Task may be started, potentially running more than the specified maximum allowed.</para>
/// <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 async Task StartAndWaitAllThrottledAsync(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.
await throttler.WaitAsync(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.
await Task.WhenAll(postTaskTasks.ToArray());
}
}
Sonra Görevler listenizi oluştururken ve bir seferde 4 eş zamanlı olarak maksimum demek olan, onları çalıştırmak zorunda işlevini çağırarak, bunu yapabilirdi yöntem, uyumsuzluğu destekler, Parallel.Invoke veya Parallel.ForEach kullanır gibi UI iş parçacığı engellemez.
Paralel görevlerin sayısını sınırlamak isterseniz, neden TPL'yi kullanmıyorsunuz? –
İş parçacığı havuzu sizin için bunu işlemek için yeterince akıllı olmalıdır. Neden kendiniz yönetmeye çalışıyorsunuz? –
[PLINQ] 'yu (http://msdn.microsoft.com/en-us/library/dd460688.aspx) kullanabilir ve [WithDegreeOfParallelism] (http://msdn.microsoft.com/en-us/library/ adresini) kullanabilirsiniz. dd383719.aspx) buna göre. –