am working on some application which involves synchronization locks.
I have a winforms application in which a method updates a variable of type integer.
I created a thread and used threadstart delegate to call the method that updates that variable. Right after the Thread.Start() call i am calling the UpdateValue method. Now since i am using Synchronization locks i thought my variable will be updated twice since updatevalue() will be called from two sperate threads plus the increment statement is within the lock statement. But to my surprise my variable is updated only once.
My code is something like this:
public partial class Form1 : Form
{
private int sharedVariable;
public Form1()
{
sharedVariable = 10;
InitializeComponent();
}
public void UpdateValue()
{
lock (this)
{
sharedVariable++;
}
}
private void Form1_Load(object sender, EventArgs e)
{
ThreadStart operation = new ThreadStart(UpdateValue);
Thread th = new Thread(operation);
th.Start();
UpdateValue();
MessageBox.Show("Value of SharedVariable is:" + sharedVariable); //this should show 12
// but is showing 11.
}
Is anywhere i am going wrong... or missing anything ?