Thread-Safe in Event Aggregator

Topics: Prism v2 - Silverlight 3, Prism v2 - WPF 3.5
Nov 25, 2009 at 8:43 AM

 

Hello,
I found there are some usages for lock as below in Prism v2. What is the main purpose of using lock(Subscriptions) in this code? Are they trying to lock the instance of Subscriptions?
As far as I know, lock method is for locking the code block (not an instance). As Subscriptions is a protected property, the child class will be able to access it and will be able to change this list. So, I think it's not thread-safe. Is this a bug or Am I missing something? 
protected ICollection<IEventSubscription> Subscriptions
{
            get { return _subscriptions; }
}

 

public virtual void Unsubscribe(SubscriptionToken token)
        {
            lock (Subscriptions)
            {
                IEventSubscription subscription = Subscriptions.FirstOrDefault(evt => evt.SubscriptionToken == token);
                if (subscription != null)
                {
                    Subscriptions.Remove(subscription);
                }
            }
        }

public virtual void Unsubscribe(SubscriptionToken token)

        {

            lock (Subscriptions)

            {

                IEventSubscription subscription = Subscriptions.FirstOrDefault(evt => evt.SubscriptionToken == token);

                if (subscription != null)

                {

                    Subscriptions.Remove(subscription);

                }

            }

        }

 

 

Nov 25, 2009 at 1:25 PM

Hi Michael,

From this article “Strictly speaking, the object provided to lock is used solely to uniquely identify the resource being shared among multiple threads, so it can be an arbitrary class instance. In practice, however, this object usually represents the resource for which thread synchronization is necessary.” That article, and this one provide a thorough explanation of the lock statement.

In this case, there can be no access to the Subscriptions protected property by any external components. Notice that for this purpose, the Subscriptions property behaves as a private property (which is recommended), as it can only be accessed through internally through your implementation of the EventBase. Therefore, if you inherit from EventBase without changing the lock on the Subscriptions property, this keeps behaving as Thread safe. If you want to access the Subscriptions property from any class that inherits from EventBase, you should consider using locks to keep your class Thread safe for any callers.

Please let me know if this helps.

Damian Schenkelman
http://blogs.southworks.net/dschenkelman