Delegates and Events

G

Guest

When multiple objects (say ClockA, ClockB, ClockC ...) from the same class
(Clocks)have the same delegate ( say secondTick) that calls the event handler
serviceClockTick, do the events stack up in a some sort of a queue, do they
preempt each other safely, does a preempting event push an existing event out
of the queue, or do they run amok? This example assumes that all the clocks
are closely synchronised and call the event handler pretty much
simultaneously. Please comment.

I'm finding that with this example with six clocks the event handler misses
at least one event, sometimes two, on a regular basis. Any solutions?
 
G

Guest

Hi,

Everytime you delegate an event using += is adding the callback reference to
a queue, this queue is executed as FIFE (First in First executed), because
you have several clocks running the same event and maybe at the same time you
should include thread safe to the function. I suspect that both calls are
trying to use the same function and clashes because MutEx (Mutual Exclusion).
Try to lock the function and see if the problem is still on.

Hope this helps
Salva
 
G

Guest

Hi,

Everytime you delegate an event using += is adding the callback reference to
a queue, this queue is executed as FIFE (First in First executed), because
you have several clocks running the same event and maybe at the same time you
should include thread safe to the function. I suspect that both calls are
trying to use the same function and clashes because MutEx (Mutual Exclusion).
Try to lock the function and see if the problem is still on.

Hope this helps
Salva
 
G

Guest

This explains a lot. Thank you. How do I add thread safety and lock the
function?
 
G

Guest

Hi

In order to lock a function you need to lock the object, if you want to lock
all the function you can use "this" object.

private static void MyFnc()
{
lock (this)
{
// Executes
}
}

This lock is for reading and writing, so if two threads try to execute the
function one will wait for the other to finish. If you need more control you
can have a ReadLock or a WriteLock so you can have more control over the
locking environment. Finally you can lock a single object like:

lock (MyCollection)
{

}

Hope this helps,
Regards
 

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

Top