0

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 ?

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by LizR
0

Sure your thread update has occured by the time your messagebox shows?
Try adding a sleep in before the messagebox to be sure.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.