I`m trying to advance a static (int) counter using two different threads in a FOR loop, so if the loop is runs 10 times I (should) get counter=20. for some reason i keep getting different values each time i run the loop (19,20,21), even though i used a LOCK to access that counter, (the code runs in console):
public static int Counter = 0;
static object syncObject = new object();
static void Main(string[] args)
{
int ForLength = 10;
Thread FirstThread, SecondThread;
for (int i = 0; i <= ForLength; i++)
{
FirstThread = new Thread(RaiseCounter);
FirstThread.IsBackground = false;
SecondThread = new Thread(RaiseCounter);
SecondThread.IsBackground = false;
FirstThread.Start();
SecondThread.Start();
//Console.WriteLine(Counter);
}
Console.WriteLine(Counter);
Console.ReadLine();
}
public static void RaiseCounter ()
{
lock (syncObject)
{
Counter++;
}
}