I have a large number of tasks (~ 1000) that need to be completed. I work on a 4-core processor, so I would like to process 4 tasks at the same time, in parallel.
To give you a starting point, here are some sample code.
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()));
}
}
I would like to receive information about which classes I will use, and how I would structure ProcessOperationsto process up to 4 operations at a time, until all operations are completed, in one expected Task.
I am thinking about using an object SemaphoreSlimin some way, as it seems to be designed to throttle a resource / process.