gpt4 book ai didi

c# - SemaphoreSlim 没有限制任务

转载 作者:行者123 更新时间:2023-11-30 19:35:22 30 4
gpt4 key购买 nike

我创建了以下方法 TestThrottled 来尝试限制我的任务,但它根本没有限制,当我调用 WhenAll 并且此方法都具有相同的耗时时。我做错了什么吗?

    private static async Task<T[]> TestThrottled<T>(List<Task<T>> tasks, int maxDegreeOfParallelism)
{
var semaphore = new SemaphoreSlim(maxDegreeOfParallelism);
var tasksParallelized = new List<Task<T>>();

foreach (var task in tasks)
{
var taskParallelized = Task.Run(async () =>
{
try
{
await semaphore.WaitAsync();

return await task;
}
finally
{
semaphore.Release();
}
});
tasksParallelized.Add(taskParallelized);
}

return await Task.WhenAll(tasksParallelized);
}

private static async Task<int> TestAsync()
{
await Task.Delay(1000);

return 1;
}

static async Task Main(string[] args)
{
var sw = Stopwatch.StartNew();

var tasks = new List<Task<int>>();
var ints = new List<int>();

for (int i = 0; i < 30; i++)
{
tasks.Add(TestAsync());
}
ints.AddRange(await TestThrottled(tasks, 1));

Console.WriteLine($"{sw.ElapsedMilliseconds}, count: {ints.Count}");
Console.ReadLine();
}

最佳答案

我解决了我的问题(创建一个通用的节流任务运行器接收异步方法列表),如下所示:

    private static async Task<T[]> RunAsyncThrottled<T>(IEnumerable<Func<Task<T>>> tasks, int maxDegreeOfParallelism)
{
var tasksParallelized = new List<Task<T>>();

using (var semaphore = new SemaphoreSlim(maxDegreeOfParallelism))
{
foreach (var task in tasks)
{
var taskParallelized = Task.Run(async () =>
{
await semaphore.WaitAsync();
try
{
return await task.Invoke();
}
finally
{
semaphore.Release();
}
});
tasksParallelized.Add(taskParallelized);
}

return await Task.WhenAll(tasksParallelized);
}
}

private static async Task<int> TestAsync(int num)
{
await Task.Delay(1000);

return 1 + num;
}

static async Task Main(string[] args)
{
var sw = Stopwatch.StartNew();

var tasks = new List<Func<Task<int>>>();
var ints = new List<int>();

for (int i = 0; i < 10; i++)
{
tasks.Add(() => TestAsync(12000));
}

ints.AddRange(await RunAsyncThrottled(tasks, 1000));

Console.WriteLine($"{sw.Elapsed.TotalMilliseconds}, count: {ints.Count}");
Console.ReadLine();
}

关于c# - SemaphoreSlim 没有限制任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176304/

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