I am not sure what you are trying to do but if you wish to update a shared variable from different threads, here are a couple of suggestions.
For simple operations like addition or incrementing use the Interlocked
class, it is very efficient.
public async Task BucketsInterlocked()
{
int bucket1 = 0;
int bucket2 = 0;
int sharedBucket = 0;
Task bucket1Task = Task.Run( () =>
{
for (int i = 0; i < 5; i++)
{
bucket1+=i;
Thread.Sleep(15);
Interlocked.Add(ref sharedBucket, i);
}
});
Task bucket2Task = Task.Run( () =>
{
for (int i = 5; i < 10; i++)
{
bucket2+=i;
Thread.Sleep(10);
Interlocked.Add(ref sharedBucket, i);
}
});
await Task.WhenAll(bucket2Task, bucket1Task);
}
For more complex operations use the
SemaphoreSlim
class, set up to limit access to the shared variable to one thread at a time.
public async Task BucketsSemaphoreSlim()
{
List<int> bucket1 = new List<int>();
List<int> bucket2 = new List<int>();
List<int> sharedBucket = new List<int>();
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);
Task bucket1Task = Task.Run(async () =>
{
for (int i = 0; i < 5; i++)
{
bucket1.Add(i);
Thread.Sleep(15);
await semaphoreSlim.WaitAsync();
sharedBucket.Add(i);
semaphoreSlim.Release();
}
});
Task bucket2Task = Task.Run(async () =>
{
for (int i = 5; i < 10; i++)
{
bucket2.Add(i);
Thread.Sleep(10);
await semaphoreSlim.WaitAsync();
sharedBucket.Add(i);
semaphoreSlim.Release();
}
});
await Task.WhenAll(bucket2Task, bucket1Task);
}
I would not recommend the DIY creation and marshalling of threads. In my experience, it nearly always results in head banging.