Thanks to
RickZeeland. This is a simple working example:
private async void button1_Click(object sender, EventArgs e)
{
await WriteThem();
Console.WriteLine("FINISHED ALL in button click");
}
public async Task Write(string s)
{
for ( int i=0; i <= 3; i++)
Console.WriteLine(s.ToUpper() +" - "+ i.ToString().PadLeft(2, '0'));
await Task.Delay(100);
Console.WriteLine($"finished {s}");
}
public async Task WriteThem()
{
Console.WriteLine("started WriteThem");
await Task.Delay(1000);
var block = new ActionBlock<string>( async _ => { await Write(_); } ,
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 });
List<string> names = new List<string>();
names.Add("task 01");
names.Add("task 02");
names.Add("task 03");
names.Add("task 04");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
try
{
foreach (string s in names)
{
block.Post(s);
}
block.Complete();
await block.Completion;
stopwatch.Stop();
Console.WriteLine("FINISHED in WriteThem: " + stopwatch.Elapsed);
}
catch (Exception n)
{
Console.WriteLine(n.Message);
}
}