我可以快捷方式通过使用一个事件来创建我的AsyncResult的开始/结束异步模式?我的、快捷方式、结束、模式

2023-09-06 23:05:41 作者:所遇皆良人

我想轻松地创建异步方法为我的WCF服务。我知道这样做的方法是使用的开始/结束异步模式,和标签我的Begin方法与AsyncPattern = TRUE。我想知道如果我真的需要作出自己的AsyncResult对象来处理(这我有点担心这样做),或者,如果我可以用一个事件处理程序和实质上缠上了我的开始/结束周围的事件处理程序的开始/结束调用。这似乎是一个迂回的方式这样做的,但因为(据我所知),我不能同意,或直接调用WCF从它似乎是一个合理的解决方案的情况下。

I would like to easily create asynchronous methods for my WCF service. I know the way to do this is to use the Begin/End async pattern, and labeling my Begin method with AsyncPattern=true. I'm wondering if I really need to make my own AsyncResult object to handle (which I'm a bit nervous about doing) or if I can use an event handler and essentially wrap my Begin/End around the event handler's Begin/End invoke. This seems like a round-about way of doing this, but since (as far as I know) I can't subscribe or invoke the event directly from WCF it seems like a plausible solution.

private event EventHandler<RequestEventArgs> OnSendRequest;

[OperationContract(AsyncPattern = true)]  // Borrowed from the interface for this example
public IAsyncResult BeginSendRequest(Request request, AsyncCallback callback, object state)
{
    EventHandler<RequestEventArgs> handler = OnSendRequest;
    if (handler != null)
        return handler.BeginInvoke(this, new RequestEventArgs(request), callback, handler);
    return null;
}

public void EndSendRequest(IAsyncResult result)
{
    EventHandler<RequestEventArgs> handler = (EventHandler<RequestEventArgs>)result.AsyncState;
    handler.EndInvoke(result);
}

然后,很明显,一些订阅事件做的工作。我也扔掉对象状态传递给我的Begin方法,有利于传递事件处理程序的状态,所以我有机会获得它调用EndInvoke。

Then, obviously, something subscribes to the event to do the work. I'm also throwing away the object state passed in to my Begin method, in favor of passing the event handler as the state so I have access to it to call EndInvoke.

这是一个可行的选择? (我有限的知识和了解如何AsyncResult对象和一般工作异步编程。)

Is this a viable option? (I have limited knowledge and understanding of how the AsyncResult object and asynchronous programming in general work.)

推荐答案

结帐无扩展的.NET(RX)。这是您正在寻找的模式的实现。

Checkout Reactive Extensions for .NET (Rx). This is an implementation of the pattern that you are looking for.

由于例如的:

var client = new WebClient();
var searchUri = new Uri("http://search.twitter.com/search.json?q=4sq.com");
var uploadUri = new Uri("http://localhost:8080/uploads");

IObservable<Unit> query =
    from result in client.DownloadStringAsObservable(searchUri, new object())
    let transformed = TransformResult(result)
    from upload in client.UploadStringAsObservable(
        uploadUri,
        "POST",
        transformed,
        new object())
    select upload;

var subscription = query.Subscribe(
    x => {}, // Nothing to do
    exn => 
    {
        // Do something with the exception
    }, 
    () => 
    {
        // Indicate we're finished
    });