Safely Raising Events in Multithreaded app.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

This questions is in reference to the article on Using Events in the C#
Programmers Reference
(http://msdn2.microsoft.com/en-us/library/ms173168.aspx).

Under the Rasing Events section it says in order to avoid a race condition
copy the event to a temporary variable before invoking it. That makes sense.
My question is is this: if we really want this to be thread safe why doesn't
this copy have to be within a locked block. For example, wouldn't this be a
better solution:

lock (this)
{
// Safely invoke an event:
TestEventDelegate temp = TestEvent;
}

if (temp != null)
{
temp(this, new System.EventArgs());
}

Or is there something I'm missing here?

Thanks,
 
Agreed, your solution stops one thread copying the TestEvent object to
temp whilst another thread may be updating TestEvent.
 
lock(this) wouldn't help anything if another thread wanted to add
subscription to the event.
It does not protect that the event would get changed (lock(this) is not
freeze every write in this class, and generally should not be used).

The meaning of taking a temp reference is that if the last subscriber of the
event unsubscribes, the TestEvent would be null and the TestEvent() call
would fail for null reference. Instead, you take the reference to a temp
var. If the var was not null, it won't be null thereafter, even if the last
subscriber unsubscribes. The temp var is still not null.
Hence the temp() call will not crash even if there are no subscribers left.
It will at most be a nop.


"smkramer072fdasfasdf" <[email protected]> ha
scritto nel messaggio
news:[email protected]...
 
Very true, lock blocks access to a block of code in an object from
multiple threads. Putting a lock around the copy of the thread only
stops more than one thread copying the event at the same time if they
are invoking the method in the same object (i.e. all have a reference
to the object that contains the method).
 

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

Back
Top