私の知る限り、すべてのイベントサブスクライバーがThreadOption.PublisherThread
オプション(デフォルトでもあります)を使用している場合、イベントは同期的に実行され、サブスクライバーはEventArgs
オブジェクトを変更できるため、パブリッシャーで使用できます。
myEventAggregator.GetEvent<MyEvent>().Publish(myParams)
if (myParams.MyProperty)
{
// Do something
}
サブスクライバーコードは次のようになります。
// Either of these is fine.
myEventAggregator.GetEvent<MyEvent>().Subscribe(MySubscribedMethod)
myEventAggregator.GetEvent<MyEvent>().Subscribe(MySubscribedMethod, ThreadOption.PublisherThread)
private void MySubscribedMethod(MyEventArgs e)
{
// Modify event args
e.MyProperty = true;
}
CompositePresentationEvent<T>
イベントを常に同期的に呼び出す必要があることがわかっている場合は、メソッドをオーバーライドするイベントの独自の基本クラスを(ではなく)作成し、Subscribe
サブスクライバーのみにThreadOption.PublisherThread
オプションの使用を許可できます。次のようになります。
public class SynchronousEvent<TPayload> : CompositePresentationEvent<TPayload>
{
public override SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<TPayload> filter)
{
// Don't allow subscribers to use any option other than the PublisherThread option.
if (threadOption != ThreadOption.PublisherThread)
{
throw new InvalidOperationException();
}
// Perform the subscription.
return base.Subscribe(action, threadOption, keepSubscriberReferenceAlive, filter);
}
}
次に、から派生する代わりに、から派生MyEvent
しCompositePresentationEvent
ますSynchronousEvent
。これにより、イベントが同期的に呼び出され、変更されたが取得されることが保証されますEventArgs
。