Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some of the alternatives to the Event-based Asynchronous Pattern?

I am looking at implementing an API where multiple operations can run concurrently. The Event-based Asynchronous Pattern has been recommended by MS:

// Asynchronous methods.
public void Method1Async(string param, object userState);
public event Method1CompletedEventHandler Method1Completed;

public void CancelAsync(object userState);
public bool IsBusy { get; }

However this seems a little clumsy to be - it requires clients to filter out replies which are not meant for them and disconnect the event handler when done etc. What I thinking is something more like:

AsyncOperation1(string parm, Action<T> callback)

Each client gets get's its own results delivered directly. I am having trouble figuring out how to support cancelation elegantly. I guess the obvious thing is for AsyncOperation1 to return some kind of token which can be passed into a CancelAsync method. I'd like to find out more about what other async patterns are in common usage in .Net or in other languages that can be translated appropriately

like image 761
Shane Avatar asked Oct 10 '22 07:10

Shane


1 Answers

Take a look at Reactive Extensions, you can return an Observable which can be subscribed to by the clients.

The subscription returns an object that implements IDisposable which is the mechanism to cancel the subscription, just dispose of the object.

For example:

IObservable<T> o = Method1Async(params);

var observer = o.Subscribe(r => {/*do stuff with the result*/},
                           ex => {/* do stuff with the exception */);

// decide to cancel
observer.Dispose();

You can install the Reactive Extensions bits using nuget, just "install-package rx-main"

like image 198
Matt Avatar answered Oct 13 '22 01:10

Matt