1

I'm wondering if there is a way to get the result from published event within single method. I have a wcf service and here is the implementation of one of its methods:

public Result DisplayMessage(string message)
{
     // some error handling
     if(errorOccurred)
     {
         return new Result { IsError = true, ErrorMessage = "error occurred"}
     }

     eventAggregator.GetEvent<DisplayMessageEvent>().Publish(new DisplayMessageEventArg(message));

     return new Result { IsError = false, ErrorMessage = String.Empty };
}

As you can see my wcf method returns the result which informs the caller if the error occurred or not. I can do some error handling before publish the event but if something happens on the DisplayMessageEvent subscriber side I want also return the result about this. Normally I would do something like DisplayMessageConfirmationEvent and from subscriber send this event to the publisher, but how to do this within single method? So in other words basically what I want to do is to publish the event, wait for the result from the subscriber and return it to the WCF caller. Any ideas?

SteppingRazor
  • 1,222
  • 1
  • 9
  • 25

1 Answers1

3

The EventAggregator is for fire-and-forget messaging only. Probably you want to use some other kind of messaging system that supports messages with results.

That being said, you can wait for another event and then continue with your method:

public Result DisplayMessage(string message)
{
     // some error handling
     if(errorOccurred)
     {
         return new Result { IsError = true, ErrorMessage = "error occurred"}
     }

     eventAggregator.GetEvent<DisplayMessageEvent>().Publish(new DisplayMessageEventArg(message));

     var result = new TaskCompletionSource<Result>();
     eventAggregator.GetEvent<DisplayMessageAnswerEvent>().Subscribe( x => result.SetResult( x ) );

     return result.Result;
}

with DisplayMessageAnswerEvent being a PubSubEvent<Result>...

Be aware that the subscriber of the original event has to always send the answer, otherwise you're stuck forever.

Haukinger
  • 10,420
  • 2
  • 15
  • 28
  • Thank you, This works exactly how I wanted to. Marked as answered. Just out of curiosity you mentioned about "other messaging systems" - could you provide me with some examples? I mean just a brief list with libraries so I can read about them. – SteppingRazor Oct 12 '16 at 09:24
  • 1
    There are loads of them out there, this really depends on what you need. One process, multiple processes on one machine, multiple processes on multiple machines, cluster-features like failover... this is a bit older, but contains several: http://stackoverflow.com/questions/1545442/net-service-bus-recommendations – Haukinger Oct 12 '16 at 10:26