Z
The use of TPL and async/await for such things is not a modern practice.Like you can use it. BufferBlockas described https://ru.stackoverflow.com/a/431145/10105 ♪ In doing so, your code will be approximately the same (I added consolation to show how the program works):class Program
{
static async Task Main(string[] args) => await new Program().Run();
async Task Run()
{
// инициализация данных
List<String> info = new List<String>();
for (int i = 1; i <= 10; ++i)
info.Add($"info{i}");
// очередь заданий
BufferBlock<string> queue = new BufferBlock<string>();
var p = Produce(queue, info);
var c = ConsumeAll(queue, 4);
await Task.WhenAll(p, c, queue.Completion);
}
// поставщик
async Task Produce(ITargetBlock<string> queue, List<String> info)
{
foreach (var data in info)
await queue.SendAsync(data);
queue.Complete();
}
// потребитель
async Task ConsumeCooperative(IReceivableSourceBlock<string> queue, int number)
{
while (await queue.OutputAvailableAsync())
{
if (queue.TryReceive(out var v))
await Task.Run(() => Process(v, number));
}
}
Task ConsumeAll(IReceivableSourceBlock<string> queue, int quantity)
{
var tasks = Enumerable.Range(0, quantity)
.Select(n => ConsumeCooperative(queue, n));
return Task.WhenAll(tasks);
}
// тут ваша обработка данных
Random r = new Random();
Stopwatch sw = Stopwatch.StartNew();
void Process(string v, int consumerNumber)
{
Console.WriteLine($"Processing started, comsumer #{consumerNumber}," +
$" data {v} at {sw.Elapsed:m\\:ss\\.ff}");
Thread.Sleep(1000 * r.Next(5, 10));
Console.WriteLine($"Processing finished, comsumer #{consumerNumber}," +
$" data {v} at {sw.Elapsed:m\\:ss\\.ff}");
}
}
Result:Processing started, comsumer #0, data info1 at 0:00.38
Processing started, comsumer #1, data info2 at 0:00.38
Processing started, comsumer #2, data info3 at 0:00.38
Processing started, comsumer #3, data info4 at 0:00.39
Processing finished, comsumer #1, data info2 at 0:05.41
Processing finished, comsumer #0, data info1 at 0:05.41
Processing started, comsumer #1, data info5 at 0:05.41
Processing started, comsumer #0, data info6 at 0:05.41
Processing finished, comsumer #3, data info4 at 0:05.43
Processing started, comsumer #3, data info7 at 0:05.44
Processing finished, comsumer #2, data info3 at 0:07.42
Processing started, comsumer #2, data info8 at 0:07.42
Processing finished, comsumer #0, data info6 at 0:10.42
Processing started, comsumer #0, data info9 at 0:10.42
Processing finished, comsumer #3, data info7 at 0:11.44
Processing started, comsumer #3, data info10 at 0:11.45
Processing finished, comsumer #1, data info5 at 0:12.44
Processing finished, comsumer #2, data info8 at 0:14.45
Processing finished, comsumer #3, data info10 at 0:17.48
Processing finished, comsumer #0, data info9 at 0:18.46