我有大量的任务(约1000个)需要执行。我的电脑是4核处理器,所以我想同时并行处理4个任务。
以下是示例代码,供您参考。
class Program
{
public class LongOperation
{
private static readonly Random RandomNumberGenerator = new Random(0);
const int UpdateFrequencyMilliseconds = 100;
public int CurrentProgress { get; set; }
public int TargetProcess { get; set; }
public LongOperation()
{
TargetProcess = RandomNumberGenerator.Next(
(int)TimeSpan.FromSeconds(5).TotalMilliseconds / UpdateFrequencyMilliseconds,
(int)TimeSpan.FromSeconds(10).TotalMilliseconds / UpdateFrequencyMilliseconds);
}
public async Task Execute()
{
while (!IsCompleted)
{
await Task.Delay(UpdateFrequencyMilliseconds);
CurrentProgress++;
}
}
public bool IsCompleted => CurrentProgress >= TargetProcess;
}
static void Main(string[] args)
{
Task.Factory.StartNew(async () =>
{
var operations = new List<LongOperation>();
for(var x = 1; x <= 10; x++)
operations.Add(new LongOperation());
await ProcessOperations(4, operations);
}).Wait();
}
public static async Task ProcessOperations(int maxSimultaneous, List<LongOperation> operations)
{
await Task.WhenAll(operations.Select(x => x.Execute()));
// TODO: Process up to 4 operations at a time, until every operation is completed.
}
}
我想请你提供一些关于使用哪些类以及如何构建ProcessOperations
以每次处理最多4个操作直到完成所有操作的输入,以便在单个可等待的Task
中。
我考虑使用SemaphoreSlim
对象,因为它似乎适用于限制资源/进程的速率。
List<LongOperation>
替换为一个ActionBlock<LongOperation>
并设置并行限制即可。 - Scott Chamberlain