Synchronizing raising of events and adding delegates to them

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.
 
J

Jon Skeet [C# MVP]

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.
 
M

mczard

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?
 
J

Jon Skeet [C# MVP]

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.
 

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