I have several threads that write to the same int. Each thread increment the
integer value. What is the simple way to synchronize the increment operation.
The lock statement works only on Object so i can’t use it. I tried also the
following:
static int number=0;
static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(strtThread);
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
Console.ReadLine();
}
public static void strtThread()
{
bool lockTaken = false;
Monitor.Enter(number,ref lockTaken);
try
{
Random rd = new Random();
int ee = rd.Next(1000);
Console.WriteLine(ee);
Thread.Sleep(ee);
number++;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (lockTaken)
{
Monitor.Exit(number);
}
}
}
It gives me the following error:
Object synchronization method was called from an unsynchronized block of code.
You can use the Interlocked.Increment Method to automically increment an integer without locking:
If you have multiple statements, you can create an object instance that you can lock: