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);
}
}
}
它给我留下以下错误:
提出反对的同步方法来自不同步的法典体。