C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Interview   Jobs   Projects   Offshore Development    
Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing | Talk to Us |



My Profile

Gifts

Active Members
TodayLast 7 Days more...







Thread-safe events


Posted Date: 11 Jul 2007    Resource Type: Articles    Category: .NET Framework

Posted By: Prajnan Das       Member Level: Gold
Rating:     Points: 10



Introduction



Thread safe code can be written around the add and remove construct of an event. Similarly while rasing an event a lock can be acquired upon to correctly get the most recent list of registered delegates in a thread safe way. This article explains these techniques for writing thread safe events.

Thread Safety around Add and Remove constructs



Events are nothing but a set of add and remove property like constructs around a private delegate instance. If thread safety is desired for an event in true sense; we need to write the body of these constructs ourselves instead of the relying on the compiler. What does thread safety in true sense means for events? Basically; we are considering the following aspects:
Add and remove don't interfere with each other
There is no over writting of delegates if two threads happen to register delegates at the same time. Similarly a removal doesn't miss out. Let's define one example:


public delegate void TestDelegate(object sender, EventArgs e);

public class ThreadSafeEventsDemo
{
// Delegate variable backing the TestEvent event.
TestDelegate testDelegate;

// Lock for TestEvent delegate access.
readonly object eventLock = new object();

public event TestDelegate TestEvent
{
add
{
lock (eventLock)
{
testDelegate += value;
}
}
remove
{
lock (eventLock)
{
testDelegate -= value;
}
}
}

///
/// Raises the TestEvent event
///

protected virtual void OnTestEvent(EventArgs e)
{
TestDelegate handler;
lock (eventLock)
{
handler = testDelegate;
}
if (handler != null)
{
handler(this, e);
}
}
}


Here we are using a read only private field as a common lock for adding/ removing of delegates and as well as raising the event. Note that events can be static as well. Then the lock variable also needs to static. Typically the lock in such cases can be taken out as typeof(<class name declaring the event>).

Raising events in a thread safe manner



Now let us come to the point of raising events in a thread safe manner. Inside the OnTestEvent() method; the current underlying delegate is assigned agianst a local variable inside the lock. This ensures the most recent list of delegates are invoked in and no addition and removal can happen in between. As delegates are immutable objects and as a copy is made inside a lock; even if the variable testDelegate changes after coming out of the lock the variable handler doesn't. This ensures that all the registered delegates till the point of invocation are called in.

Summary


Simple thread safety code while defining and invoking events are discussed. If we are not in complete control of our events and the event is typically defined to be part of a class library which is going to be used by different threads; thread safety code for events would be important.





Responses

Author: Allen B. Taylor    07 Aug 2007Member Level: Bronze   Points : 0
I agree that the lock is necessary to ensure that multiple adders and removers don't clobber each other, but since delegates are immutable objects, I don't see how the lock is necessary in the OnTestEvent method in the example. The delegate (testDelegate in this case) will never be in an indeterminate state; it simply gets replaced with a new immutable delegate after an add or remove, so it can be read without the need for locking.

Also, the example code fails to handle the case where one of the clients throws an exception. Such a case causes all other clients in the list to miss the event. This issue is dealt with in many other places, so I won't elaborate here.


Author: Anthony    28 May 2008Member Level: Bronze   Points : 2
I just read this exact example at another web page. It is a very good, comprehensive article about delegates and events.

http://www.yoda.arachsys.com/csharp/events.html


Author: Mahesh Raj    07 Jun 2008Member Level: Gold   Points : 1
This is very good information,Continue posting such useful articles.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Demystifying Delegates and Events in C#
Previous Resource: An Exploitation of ADO.NET DataSet: Establishing Relationships among Heterogenous Data Sources
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

accuconference

Contact Us    Privacy Policy    Terms Of Use