Synchronization In Timers

M

Mike Bird

I have a WinForms application with a timer. When the timer tick event is
running, I may pop up a MessageBox. Since the message box can cause me to
be inside the timer tick event handler for a long period of time, I wanted
to ensure that all future timer ticks are ignored until I exit process the
current one.

I have tried a lock(timerInstance) around the timer code with no luck.
I have tried a Monitor.TryEnter(timerInstance, 0) around the timer code,
also no help.
I have tried creating a Mutex for my class and performing a Mutex.WaitOne(0,
false) around my timer code with no success.

It appears that timer event and thread synchronization do not mix, but I am
at a loss as to why this would be. Anyone have any idea why none of these
works?
 
R

Ron McNulty

Hi Mike

I think this is a Windows "feature" rather than a .NET feature. Modal
dialogs do not stop the message queue from responding, so timer events will
continue to be serviced. You need to set a flag just before the modal dialog
is shown, and clear it on exit. Then use the flag state to decide whether to
ignore or accept each event.

If multiple threads can put up the offending dialog, you will need to do a
bit of old-fashioned synchronisation in the sections of code that set and
clear the flag, else you may get the occasional lock-up or two dialogs.

HTH

Regards

Ron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top