If you have the following problem to solve, how would you do it?
The goal is to create an array of 1000 integer values, initialized to 0 and then increment all the values using 2 threads, each thread will increment each array value by 1.
I did it with the following code but I'm really not sure my solution is ok...
static async Task Main(string[] args)
{
var count = 100;
int[] array = new int[count];
Array.Clear(array, 0, array.Length);
await Task.WhenAll(IncrementArray(array, "Task 1"), IncrementArray(array, "Task 2"));
Array.ForEach(array, Console.WriteLine);
}
static object obj = new object();
static async Task IncrementArray(int[] array, string taskName)
{
for (var i = 0; i < array.Length; i++)
{
Console.WriteLine(taskName);
await Task.Delay(100);
lock (obj)
{
array[i]++;
}
}
}
Thanks for your help!
Parallel.ForEachto do the job, that's what the method would doIncrementArray()is synchronous.await Task.Delay(1);inside theIncrementArraymethod and made itasync, you would then start to see errors as++is not thread safe.lockif you useInterlocked.Increment(ref array[i])