gpt4 book ai didi

c# - 我可以限制同时运行的 System.Threading.Tasks.Task 对象的数量吗?

转载 作者:太空狗 更新时间:2023-10-29 22:27:54 25 4
gpt4 key购买 nike

我正在使用 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 个任务,其余的等待?

最佳答案

My blog post展示了如何使用 Tasks 和 Actions 执行此操作,并提供了一个示例项目,您可以下载并运行以查看两者的实际效果。

有 Action

如果使用 Actions,您可以使用内置的 .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);

关于c# - 我可以限制同时运行的 System.Threading.Tasks.Task 对象的数量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8834045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com