You can use lock
to restrict the updating of a variable to one thread at a time. Other threads calling the method will be blocked until the lock is released.
private readonly object totalLock = new object();
private double total;
public void AdjustTotal(double amount)
{
lock (totalLock)
{
total += amount;
}
}
As an alternative, you can use the
SemaphoreSlim
class to provide the same functionality without blocking any threads in the process
private readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);
private double total;
public async Task AdjustTotalAsync(double amount)
{
await semaphoreSlim.WaitAsync();
try
{
total += amount;
}
finally
{
semaphoreSlim.Release();
}
}