Re: Concurrency and delegates
- From: Peter Duniho <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Mon, 12 Nov 2007 00:00:25 -0800
On 2007-11-11 21:42:57 -0800, Scott Gifford <sgifford@xxxxxxxxxxxxxxxx> said:
[...]
My question is, do people actually do this? It seems quite tedious,
and I've never seen it in sample code. Is there some reason I'm not
seeing why this isn't really a race condition? Is there some other
way to deal with this?
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), 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:
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/3a0c55a45e964f6c/f3b4b45776a7d7a0
Anyway,
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.
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. Maybe it's because it helps you understand how to make an event thread-safe, even though his (perfectly reasonable) reply is to suggest you just make sure you use the event in a thread-safe way instead. :)
Personally, I think either approach is fine. But you do need to concern yourself with thread-safety one way or the other, for an event used from multiple threads.
Pete
.
- Follow-Ups:
- Re: Concurrency and delegates
- From: Jon Skeet [C# MVP]
- Re: Concurrency and delegates
- References:
- Concurrency and delegates
- From: Scott Gifford
- Concurrency and delegates
- Prev by Date: Re: Help a newbie with method.method?
- Next by Date: Re: Get a file from my resource file and write it to disk
- Previous by thread: Re: Concurrency and delegates
- Next by thread: Re: Concurrency and delegates
- Index(es):
Relevant Pages
|