Hi,
I have a method that is being called by a timer. I want to lock the entire
section of the code in the method to protect it from being called
simultaneously. So I am using Monitor.Enter(this) and Monitor.Exit(this)
where this is the form object where the method is present.
But what I observed was even after this lock still I see multiple calls
accessing the code. Am I doing something wrong? Is it the way to block a
section of a code in .Net?
Thanks in advance,
Sateesh.
rajamanickam - 30 Jul 2004 14:25 GMT
Hi Sateesh..
Instead of Monitor class you can lock the block by a boolean variable....
eg
private bool IsAlreadyRunning =false;
private void timer_tick()
{
if(!IsAlreadyRunning)
{
IsAlreadyRunning=true;
your code here;
IsAlreadyRunning=false;
}
}
-rajaManickam
Jon Skeet [C# MVP] - 31 Jul 2004 07:58 GMT
> Instead of Monitor class you can lock the block by a boolean variable....
>
[quoted text clipped - 11 lines]
> }
> }
No, that's not thread-safe.
1) Different threads may not see updated values, as there's no memory
barrier there
2) Two threads could both get inside the code before either of them
sets IsAlreadyRunning to true.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Chris Dunaway - 30 Jul 2004 16:14 GMT
> Hi,
>
> I have a method that is being called by a timer. I want to lock the entire
> section of the code in the method to protect it from being called
> simultaneously. So I am using Monitor.Enter(this) and Monitor.Exit(this)
Why not stop the timer at the beginning of the code, when it is complete,
restart the timer.

Signature
Chris
dunawayc[AT]sbcglobal_lunchmeat_[DOT]net
To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
Jon Skeet [C# MVP] - 31 Jul 2004 07:59 GMT
> I have a method that is being called by a timer. I want to lock the entire
> section of the code in the method to protect it from being called
[quoted text clipped - 4 lines]
> accessing the code. Am I doing something wrong? Is it the way to block a
> section of a code in .Net?
Which kind of timer are you using? Are you calling Application.DoEvents
in your code?
Could you post a short but complete program which demonstrates the
problem?
See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
See http://www.pobox.com/~skeet/csharp/multithreading.html for general
multi-threading advice.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too