Timer and Monitor

  • Thread starter Thread starter Sateesh
  • Start date Start date
S

Sateesh

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.
 
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
 
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.

--
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.
 
rajamanickam said:
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;
}
}

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.
 
Sateesh said:
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?

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.
 
Back
Top