F
fei.liu
Hello, in the application I am developing, I am having trouble to
synchronize event triggered actions using 'lock(ob){...};' technique.
Here is a outline of my code:
class C{
int x = 0;
public void incre(){ if(x < 20) x++; }
}
class Form1: WinForm{
...//all the usual initialization setup code.
C c;
Object ob = new Object();
public void onPaint(..., ...) // event handler of a paint event
{
lock(ob){
c.incre();
}
}
pubilc void onKeyUp(..., ...) // event handler of a keyboard event
{
if(e.Key == Keys.G) // increase C.x when user presses 'g'
{
lock(ob){
c.incre();
}
}
}
}
Now, theoretically, because c.incre() call is protected by lock
synchronization, c.x should always <= 20; But to my surprise, this code
produces different result, c.x = 20 randomly. It seems my lock
synchronization did not work and two threads (paint thread, keyboard
handler thread) can execute c.x simultaneously...
If you know what I did wrong here, please advise. Thanks,
synchronize event triggered actions using 'lock(ob){...};' technique.
Here is a outline of my code:
class C{
int x = 0;
public void incre(){ if(x < 20) x++; }
}
class Form1: WinForm{
...//all the usual initialization setup code.
C c;
Object ob = new Object();
public void onPaint(..., ...) // event handler of a paint event
{
lock(ob){
c.incre();
}
}
pubilc void onKeyUp(..., ...) // event handler of a keyboard event
{
if(e.Key == Keys.G) // increase C.x when user presses 'g'
{
lock(ob){
c.incre();
}
}
}
}
Now, theoretically, because c.incre() call is protected by lock
synchronization, c.x should always <= 20; But to my surprise, this code
produces different result, c.x = 20 randomly. It seems my lock
synchronization did not work and two threads (paint thread, keyboard
handler thread) can execute c.x simultaneously...
If you know what I did wrong here, please advise. Thanks,