Synchronizing raising of events and adding delegates to them

  • Thread starter Thread starter mczard
  • Start date Start date
M

mczard

In my application events can be raised in one thread, but delegates
can be added to the events from another thread. I wonder if I really
have to synchronize the event raising and all += / -= operations.

Do I have to write:

lock ( source.NewInput ) {
source.NewInput += this.NewInputHandler;
}

and

protected virtual void OnNewInput(object sender, NewInputEventArgs e)
{
if (NewInput != null)
{
lock ( NewInput )
{
NewInput(this, e);
}
}
}


???

Without the locks my application works correctly, but I know this
doesn't proof anything.

I cannot find any info on the web, because word "event" has too many
meanings.
 
In my application events can be raised in one thread, but delegates
can be added to the events from another thread. I wonder if I really
have to synchronize the event raising and all += / -= operations.

If you care about it being thread-safe, you should.
Do I have to write:

lock ( source.NewInput ) {
source.NewInput += this.NewInputHandler;
}

and

protected virtual void OnNewInput(object sender, NewInputEventArgs e)
{
if (NewInput != null)
{
lock ( NewInput )
{
NewInput(this, e);
}
}
}

No. Those won't work.

See http://pobox.com/~skeet/csharp/threads/lockchoice.shtml for a
working pattern.
 
Seehttp://pobox.com/~skeet/csharp/threads/lockchoice.shtmlfor a
working pattern.

Thanks for that comment, but seems that equally good, but more
simple will be to write only:

protected virtual OnSomeEvent(EventArgs e)
{
SomeEventHandler handler;
lock (this)
{
handler = someEvent;
}
if (handler != null)
{
handler (this, e);
}
}

Am I right? Locking of += and -= is already done with 'this',
so why shouldn't I use it?
 
Thanks for that comment, but seems that equally good, but more
simple will be to write only:

protected virtual OnSomeEvent(EventArgs e)
{
SomeEventHandler handler;
lock (this)
{
handler = someEvent;
}
if (handler != null)
{
handler (this, e);
}
}

Am I right? Locking of += and -= is already done with 'this',
so why shouldn't I use it?

Because locking with "this" is bad practice. "this" is effectively a
publicly available reference, so you can't guarantee that something
else isn't locking on it elsewhere.
 
Back
Top