Re: Concurrency and delegates
- From: "Jon Skeet [C# MVP]" <skeet@xxxxxxxxx>
- Date: Mon, 12 Nov 2007 00:56:31 -0800
On Nov 12, 8:00 am, Peter Duniho <NpOeStPe...@xxxxxxxxxxxxxxxx> wrote:
<snip>
I believe that the basic answer is yes, if the event is supposed to be
thread-safe, people do actually do _something_ like this.
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.
but it's apparently common enough that the question of the
assignment to a local
variable being optimized out has come up before. Unfortunately, I
don't recall any thread that ever provided any conclusive statements
one way or the other on either issue (whether the technique works, and
whether it can be accidently defeated by the optimizer). Here's one
example of such a discussion though:
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.
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".
Jon Skeet wrote a good article on the topic. You might check it out,
assuming you haven't already:http://www.pobox.com/~skeet/csharp/events.html
I'm not sure why he didn't mention that article in his own reply.
I was late for work :)
<snip>
Jon
.
- 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
- Concurrency and delegates
- Prev by Date: Re: How to open a command prompt using c# coding?
- Next by Date: Using NLST to retrieve file names
- Previous by thread: Re: Concurrency and delegates
- Next by thread: Re: Concurrency and delegates
- Index(es):
Relevant Pages
|