timers and locks

P

pistmaster

Hi,

I have a timer which I use to process some events that have been added
to a queue. The processing may take longer than the timer tick and so
the timer catches up with itself. I would like to lock the timer so
that this doesn't happen, so I do:

timer_Tick()
{
if (System.Threading.Monitor.TryEnter(queue.SyncRoot))
{
try {
// process queue
} finally
{
System.Threading.Monitor.Exit(queue.SyncRoot);
}

}
}

I use TryEnter because I don't want to exhaust the thread pool but it
makes no difference. The trouble is the function doesn't actually
lock, and always processes the queue regardless. Is this because
locks just don't work in timers? Something to do with the context
being the same, like with you do:

function1()
{
lock(a)
{
function2();
}
}

function2()
{
lock(a)
{
}
}
 
K

Kevin Spencer

It is not the timer that does the processing; it is the timer's Elapsed
event handler. The timer's Elapsed event handler can check to see if the
processing is still proceeding, and pause the timer until it has finished.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
C

Christof Nordiek

Hi,

what sort of timer do you use. There are three timer classes in the
..NET-Framework, for different purposes.
You can use intellisense to see the full namspace of the timer class.

The System.Windows.Forms.Timer e.g. processes all events in the GUI-Thread.
So there would be no locking needed. Atleast not against oter timer events.

Christof
 
C

Christof Nordiek

Christof Nordiek said:
Hi,

what sort of timer do you use. There are three timer classes in the
.NET-Framework, for different purposes.
You can use intellisense to see the full namspace of the timer class.

The System.Windows.Forms.Timer e.g. processes all events in the
GUI-Thread. So there would be no locking needed. Atleast not against oter
timer events.

Christof

Seems to be the System.Wndows.Forms-Timer. This is the only one that has a
Tick-Event.
So, as I said, the Tick-Calls can't be parallel anyway and there will be no
locking between them.

But, if the processing is really so lengthy, that a tick could come, before
the preceeding call is processed, you shouldn't doe it in the GUI-Thread
anyway. This will freeze your GUI.

Christof
 

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