对于基于事件的异步模式,有哪些替代方案?

时间:2022-01-22 01:13:32

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

我正在研究实现一个API,在这个API中可以同时运行多个操作。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

每个客户端直接获得get自己的结果。我不知道如何优雅地支持取消。显然,AsyncOperation1会返回某种令牌可以传递给CancelAsync方法。我想了解更多关于在。net中或其他可以适当翻译的语言中常见的其他异步模式是什么

1 个解决方案

#1


4  

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.

订阅返回一个实现IDisposable的对象,IDisposable是取消订阅的机制,仅仅是对对象的处置。

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"

您可以使用nuget安装反应性扩展位,只需“安装-包rx-main”

#1


4  

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.

订阅返回一个实现IDisposable的对象,IDisposable是取消订阅的机制,仅仅是对对象的处置。

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"

您可以使用nuget安装反应性扩展位,只需“安装-包rx-main”