Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

How to: Subscribe and Unsubscribe to Events

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Overview

The Composite Application Library provides an event mechanism that enables communications between loosely coupled components in the application. This mechanism, based on the event aggregator service, allows publishers and subscribers to communicate through events and still do not have a direct reference to each other.

This topic describes how to subscribe and unsubscribe to an event that can be consumed in a loosely coupled way. For more information about events, see the Event Aggregator technical concept.

Prerequisites

This topic assumes that you have a solution built using the Composite Application Library that has a module and a typed event created. For information about how to do this, see the following topics:

Steps

The following procedure describes how to subscribe to a typed event.

To subscribe to a typed event

  1. If the event you want to subscribe to is defined in a project other than the project where your subscriber exists, add a reference to the event's project in the subscriber's project.
  2. In the class where you want to subscribe to the event, add the following using statements and if required, also add a using statement for the typed event's namespace. You will use the following using statements to refer to event-related classes in the Composite Application Library.
    using Microsoft.Practices.Composite.Events;
    using Microsoft.Practices.Composite.Wpf.Events;
    
    
  3. Obtain a reference to the event aggregator service (the event aggregator service implements the Microsoft.Practices.Composite.Events.IEventAggregator interface and is responsible for creating and locating event instances). To do this, you can use dependency injection by adding a parameter of type IEventAggregator to the class constructor, as shown in the following code. If the class is instantiated by a container, it will have an instance of the event aggregator service injected when it is instantiated.
    public class Class1
    {
      private IEventAggregator eventAggregator;
      public Class1(IEventAggregator eventAggregator)
      {
        this.eventAggregator = eventAggregator;
      }
      ...
    }
    
    
  4. Obtain a reference to the event you want to subscribe to by invoking the GetEvent method on the event aggregator service instance. The following example code shows how to obtain an event of type FundAddedEvent.
    FundAddedEvent fundAddedEvent = this.eventAggregator.GetEvent<FundAddedEvent>();
    
    
  5. Add a subscription to the event by invoking the Subscribe method on the event instance. The Subscribe method has several overloads that take all or some of the following parameters:
    • action. This required parameter is of type System.Action<TPayLoad> and is the callback delegate that gets executed when the event is published.
    • threadOption. This optional parameter is of type Microsoft.Practices.Composite.Wpf.Events.ThreadOption and specifies on which thread the callback delegate will be invoked. You can choose one of the following options:
      • ThreadOption.PublisherThread. Use this option to run the callback delegate in the same thread as the publisher. This is how typical .NET Framework events work; it is the default behavior when the threadOption parameter is omitted.
      • ThreadOption.UIThread. Use this option to run the callback delegate on the user interface thread. This is particularly useful if the code in the callback delegate interacts with controls in the user interface or with models bound to the user interface.
      • ThreadOption.BackgroundThread. Use this option to run the callback delegate in a new background thread.
    • keepSubscriberReferenceAlive. This parameter is of type bool. When it is true, the event instance keeps a strong reference to the subscriber instance, not allowing it to get garbage collected. If you want to dispose the subscriber instance, you must explicitly unsubscribe the subscriber from the event to avoid memory leaks or unexpected behavior. For information about how to do this, see the procedure "To unsubscribe from an event."

      If the parameter is set to false (this is the default value when omitted), the event will maintain a weak reference to the subscriber instance, allowing the garbage collector to dispose the subscriber instance when there are no other references to it. When the subscriber instance gets collected, the event will automatically unsubscribe it.

      Ff921131.note(en-us,PandP.10).gifNote:
      For more information about weak references, see Weak References.

    • filter. This parameter is of type System.Predicate<TPayLoad> and is a delegate that gets executed when the event is published to determine if the payload of the published event matches a set of criteria required to have the subscriber callback invoked. If the payload does not meet the specified criteria, the subscriber callback is not executed.

    The following example code shows different valid ways to add subscriptions to the event obtained in the previous step.

    // This subscription will run the callback delegate in the UI 
    // thread and will keep the subscriber reference alive.
    fundAddedEvent.Subscribe(FundAddedEventHandler, ThreadOption.UIThread, true);
    
    // This subscription will run the callback delegate in the 
    // publisher's thread, will not keep the subscriber reference alive,
    // and will be executed only if a particular condition is met for 
    // the payload.
    fundAddedEvent.Subscribe(FundAddedEventHandler, ThreadOption.PublisherThread, false, fundOrder => fundOrder.CustomerId == _customerId);
    
    // This is the FundAddedEventHandler event handler's signature. Note that it takes a parameter of the TPayLoad type.
    void FundAddedEventHandler(FundOrder fundOrder) { ... }
    
    
    Ff921131.note(en-us,PandP.10).gifNote:
    The Subscribe method returns a subscription token of type Microsoft.Practices.Composite.Events.SubscriptionToken that can be used to remove a subscription to the event later. This token is particularly useful when you are using anonymous delegates or lambda expressions as the callback delegate or when you are subscribing the same event handler with different filters.
    It is not recommended to modify the payload object from within a callback delegate because several threads could be accessing the payload object simultaneously. You could have the payload be immutable to avoid concurrency errors.

The following procedure describes how to remove a subscription for an event. You remove a subscription for an event when you want to stop receiving notifications or when you want to dispose your subscriber object and the subscription holds a strong reference to it.

To unsubscribe from an event

  1. Obtain a reference to the event you want to remove a subscription from by invoking the GetEvent method on the corresponding event aggregator service instance (for information about how to do this, see step 3 of the procedure "To subscribe to a typed event" earlier in this topic).
  2. Invoke the Unsubscribe method on the event instance, passing one of the following parameters:
    • The callback delegate you passed to the Subscribe method of the event when you added the subscription
    • The subscription token returned by the Subscribe method when you added the subscription
  3. The following example code shows different valid ways of invoking the Unsubscribe method on an event instance named fundAddedEvent.
    // This line removes the subscription whose subscription
    // token is subscriptionToken.
    fundAddedEvent.Unsubscribe(subscriptionToken);
    
    // This line removes the subscription whose callback delegate is 
    // FundAddedEventHandler.
    fundAddedEvent.Unsubscribe(FundAddedEventHandler);
    
    

Outcome

You will have a subscription to a typed event that receives notifications when the event is published. Optionally, your subscription will define a filter to avoid receiving notifications if the event's payload does not meet a set of criteria.

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.