Prism_Event Aggregator(4)

Event Aggregator

Prism library provides an event mechanism for communication between the components can be loosely coupled in an application. The mechanism is based event aggregator service that allows publishers and subscribers communicate through the event, but still there is no direct reference to each other.

In EventAggregatora variety of publish / subscribe functionality. This means that there can be multiple publishers triggering the same event, and there may be multiple subscribers to listen to the same event. Consider using EventAggregatorcross-module release event and send messages between business logic code (such as controllers and presenters).

Use Prism Library created the event is typed event. This means that you can use to detect errors at compile-time type checking before running the application. In the Prism Library, EventAggregatorallows the subscriber to the publisher or target specific EventBase. A plurality of event aggregator further allows a plurality of subscribers and publishers, as shown below.

Video Tutorial

Using the Event Aggregator video tutorials

IEventAggregator

EventAggregatorClasses are provided as a service in a container, and may be retrieved through IEventAggregatorthe interface. Event aggregator is responsible for locating or constructing a set of events and reservations system events.

public interface IEventAggregator
{
    TEventType GetEvent<TEventType>() where TEventType : EventBase;
}

If the EventAggregatorevent has not been constructed, the tectonic events during the first visit. This allows the publisher or subscriber need not determine whether the event is available.

PubSubEvent

Connect to the publisher and the subscriber's real work is done by PubSubEventthe class finished. EventBaseOnly to realize Prism Library contained in the class. Such maintenance subscriber list and handle events scheduled subscribers.

PubSubEventClass is a generic class, we need to be defined as the general type of payload type. This helps to force the publishers and subscribers provide the correct way to successful events connected at compile time. The following code shows the definition section PubSubEvent class.

Create an event

PubSubEvent<TPayload>The intent is for the application or module base class for a particular event. TPayLoadPayload is the type of event. Payload is when the event publishing parameters will be passed to subscribers.

For example, the following code shows TickerSymbolSelectedEvent. The payload is a string containing a company symbol. Please note that the implementation of this class is how to empty.

public class TickerSymbolSelectedEvent : PubSubEvent<string>{}
note

In the composite application, the event is often shared between a plurality of modules, so they are defined in a common position. The usual practice is shared assembly to define these events, such as "core" or "infrastructure" projects.

Publishing events

From the publisher by EventAggregatorcalling Publishto trigger event search method events. To access EventAggregator, through the IEventAggregatoruse add dependency injection type parameter class constructor.

public class MainPageViewModel
{
    IEventAggregator _eventAggregator;
    public MainPageViewModel(IEventAggregator ea)
    {
        _eventAggregator = ea;
    }
}

The following code demonstrates how to publish TickerSymbolSelectedEvent.

_eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish("STOCK0");

Subscribe to events

Subscribers can use the class Subscribeto participate in the event one of overloaded methods available PubSubEvent.

public class MainPageViewModel
{
    public MainPageViewModel(IEventAggregator ea)
    {
        ea.GetEvent<TickerSymbolSelectedEvent>().Subscribe(ShowNews);
    }

    void ShowNews(string companySymbol)
    {
        //implement logic
    }
}

There are several subscription PubSubEvents. Use the following criteria to help determine the most appropriate options for your needs:

  • If you need to be able to update the UI elements when you receive an event, subscribe to receive events on the UI thread.
  • If you need to filter events, providing a filter delegate subscription.
  • If you have questions about the performance of the event, consider using a strong reference to the commission at the time of subscription, and then manually unsubscribe PubSubEvent.
  • If none of the above apply, use the default subscription.

The following sections describe these options.

Subscribe to the UI thread

Subscribers typically need to update the UI elements in response to events. In WPF, only the UI thread can update the UI elements.

By default, subscribers receive event on a thread publisher. If the publisher send events from the UI thread, the subscriber can be updated UI. However, if the thread is a background thread publisher, the subscriber may not be able to directly update UI elements. In this case, subscribers need to use the Dispatcher class schedule update on the UI thread.

This PubSubEventhas a prism libraries can assist by allowing users to automatically receive events on the UI thread. This information indicates a subscriber, as shown in the following code sample during the subscription period.

public class MainPageViewModel
{
    public MainPageViewModel(IEventAggregator ea)
    {
        ea.GetEvent<TickerSymbolSelectedEvent>().Subscribe(ShowNews, ThreadOption.UIThread);
    }

    void ShowNews(string companySymbol)
    {
        //implement logic
    }
}

The following options are available for ThreadOption:

  • PublisherThread: Use this setting to receive event on the theme of publishers. This is the default setting.
  • BackgroundThread: Use this setting to receive asynchronous events on the .NET Framework thread pool thread.
  • UIThread: Use this setting to receive events on the UI thread.

note

To PubSubEventpublish to subscribers on the UI thread, EventAggregatorthe original must be built on the UI thread.

Subscribe to filter

Subscribers may need to deal with each instance of published events. In these cases, the subscriber can use a filter parameter. It is the type of filter parameters, System.Predicate<TPayLoad>and was commissioned to perform at the release event to determine whether a published event payload and invoke a set of conditions required for the subscriber callback match. If you do not satisfy the conditions specified in the payload, the subscriber callback is not executed.

Typically, the filter as a lambda expression to provide, as the following code example.

public class MainPageViewModel
{
    public MainPageViewModel(IEventAggregator ea)
    {
        TickerSymbolSelectedEvent tickerEvent = ea.GetEvent<TickerSymbolSelectedEvent>();
        tickerEvent.Subscribe(ShowNews, ThreadOption.UIThread, false, 
                              companySymbol => companySymbol == "STOCK0");
    }

    void ShowNews(string companySymbol)
    {
        //implement logic
    }
}
note

This Subscribemethod returns a token type of subscription Prism.Events.SubscriptionToken, it can be used to delete subscriptions to the event later. When you use an anonymous delegate or lambda expression as a callback delegate, or use different filters to subscribe the same event handler, this marker is particularly useful.

note

It recommended not to modify the payload object callback delegate because multiple threads may simultaneously access the payload object. You can not change the payload to avoid concurrency errors.

Use strong reference Subscribe

If you make more than one event in a short time and took note of their performance problems, you may need to use a strong delegation references to subscribe. If you do so, you need to manually when disposing of subscribers to unsubscribe to the event.

By default, PubSubEventthe maintenance of subscribers handler delegate weak references and subscription filter. This means that PubSubEventto retain a reference to the garbage collector does not prevent subscribers. Use weak references may delegate unsubscribe from the subscriber and to allow correct garbage collection.

However, maintaining this commission cited weak slower than the corresponding strong references. For most applications, this performance will not be obvious, but if your application publishing a number of events in a short time, you may need to use strong references to PubSubEvent. If you do use a strong delegation reference, the subscriber should cancel your subscription, to enable proper garbage collection when no longer use the subscription object.

To subscribe strong reference, use the method keepSubscriberReferenceAliveparameters on Subscribe, as the following code example.

public class MainPageViewModel
{
    public MainPageViewModel(IEventAggregator ea)
    {
        bool keepSubscriberReferenceAlive = true;
        TickerSymbolSelectedEvent tickerEvent = ea.GetEvent<TickerSymbolSelectedEvent>();
        tickerEvent.Subscribe(ShowNews, ThreadOption.UIThread, keepSubscriberReferenceAlive, 
                              companySymbol => companySymbol == "STOCK0");
    }

    void ShowNews(string companySymbol)
    {
        //implement logic
    }
}

keepSubscriberReferenceAliveType of the parameter bool:

  • Set a time true, event instances retains strong references to the subscriber instance, not allowing it to collect garbage. Information about how to cancel subscriptions, please see later in this topic "unsubscribe event".
  • When set to false(default value of this parameter is omitted), the event maintains a weak reference to an example of the subscriber, allowing the subscriber garbage collector configuration example when no other references. After collecting subscriber instance, will automatically unsubscribe the event.

Subscribe to cancel the event

If you no longer wish to receive subscriber activity, you can use the handler subscribers to unsubscribe, you can use the token to subscribe unsubscribe.

The following code example shows how to unsubscribe directly handlers.

public class MainPageViewModel
{
    TickerSymbolSelectedEvent _event;
    public MainPageViewModel(IEventAggregator ea)
    {
        _event = ea.GetEvent<TickerSymbolSelectedEvent>();
        _event.Subscribe(ShowNews);
    }

    void Unsubscribe()
    {
        _event.Unsubscribe(ShowNews);
    }

    void ShowNews(string companySymbol)
    {
        //implement logic
    }
}

The following code example shows how to unsubscribe from the subscription token. As a return value token provided Subscribe.

public class MainPageViewModel
{
    TickerSymbolSelectedEvent _event;
    SubscriptionToken _token;
    public MainPageViewModel(IEventAggregator ea)
    {
        _event = ea.GetEvent<TickerSymbolSelectedEvent>();
        _token = _event.Subscribe(ShowNews);
    }

    void Unsubscribe()
    {
        _event.Unsubscribe(_token);
    }

    void ShowNews(string companySymbol)
    {
        //implement logic
    }
}

Guess you like

Origin www.cnblogs.com/lovexinyi/p/11068941.html