Re: Concurrency and delegates
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Mon, 12 Nov 2007 19:38:41 -0000
Peter Duniho <NpOeStPeAdM@xxxxxxxxxxxxxxxx> wrote:
One technique I've seen suggested doesn't use locking at all. It just
copies the event. I'm not really clear on why that's considered
thread-safe (it doesn't seem to me that it would be),
It's thread safe in that it won't throw a NullReferenceException.
However, it won't necessarily use the latest value of the variable
unless there are memory barriers in place.
So, copying the event instance is an atomic operation? Is that because
there's some behind-the-scenes locking going on? Or is it because the
event can be copied in a single CPU-atomic operation?
Reference assignments are always atomic - that's guaranteed under all
the memory models I've seen.
I believe the consensus is that under the MS CLR 2.0 memory model,
it's safe - but it's not *strictly speaking* safe under ECMA.
So what are the chances it could change in the future? Is this
something that people should be cautioned to avoid relying on? Or is
this one of those things that so much code would break if Microsoft
changes the model that they would never change it in a way that would
break this?
The latter - the situation suggested is basically insane. If you can't
rely on local variables being "safe" then life becomes impossible.
that's a long way of saying that I think the last example you posted is
in fact the close to the recommended practice for thread-safe
event-raising. The only discrepancy would be the use of "this" as
opposed to a dedicated object instance for locking.
And holding the lock while calling the other code - a definite "no-
no".
Well, the last example in Scott's post didn't have that problem. :)
Indeed - somehow I'd missed that.
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: Concurrency and delegates
- From: Peter Duniho
- Re: Concurrency and delegates
- References:
- Concurrency and delegates
- From: Scott Gifford
- Re: Concurrency and delegates
- From: Peter Duniho
- Re: Concurrency and delegates
- From: Jon Skeet [C# MVP]
- Re: Concurrency and delegates
- From: Peter Duniho
- Concurrency and delegates
- Prev by Date: Re: Table bloat in Linq-SQL
- Next by Date: Re: Delegates vs. MethodInfo When Calling Code Dynamically
- Previous by thread: Re: Concurrency and delegates
- Next by thread: Re: Concurrency and delegates
- Index(es):
Relevant Pages
|