1

Let's say I have code that uses the Asynchronous Programming Model, i.e. it provides the following methods as a group which can be used synchronously or asynchronously:

public MethodResult Operation(<method params>);

public IAsyncResult BeginOperation(<method params>, AsyncCallback callback, object state);
public MethodResult EndOperation(IAsyncResult ar);

What I want to do is wrap this code with an additional layer that will transform it into the event-driven asynchronous model, like so:

public void OperationAsync(<method params>);
public event OperationCompletedEventHandler OperationCompleted;
public delegate void OperationCompletedEventHandler(object sender, OperationCompletedEventArgs e);

Does anyone have any guidance (or links to such guidance) on how to accomplish this?

4

2 回答 2

2

See "Async without the pain" for some thoughts on this; the code supplied uses a callback approach, but events would be easy enough if you drop it on an instance.

public static void RunAsync<T>(
    Func<AsyncCallback, object, IAsyncResult> begin,
    Func<IAsyncResult, T> end,
    Action<Func<T>> callback) {
    begin(ar => {
        T result;
        try {
            result = end(ar); // ensure end called
            callback(() => result);
        } catch (Exception ex) {
            callback(() => { throw ex; });
        }
    }, null);
}
于 2009-11-09T16:55:01.733 回答
2

您可以使用 AsyncFunc 库进行包装。

http://asyncfunc.codeplex.com

代码如下所示:

public class Original
{
    public ResultType Operation(ParamType param){...}
    public IAsyncResult BeginOperation(ParamType param, AsyncCallback callback, object state){...}
    public ResultType EndOperation(IAsyncResult ar){...}
}

public class Wrapper
{
    private AsyncFunc<ParamType, ResultType> _operation;
    private Original _original;

    public Wrapper(Original original)
    {
        _original = original;
        _operation = AsyncFunc<ParamType, ResultType>(_original.Operation);
    }

    public ResultType Operation(ParamType param)
    {
        return _original.Operation(param);
    }

    public void OperationAsync(ParamType param)
    {
        _operation.InvokeAsync(param)
    }

    public event AsyncFuncCompletedEventHandler<ResultType> OperationCompleted      
      {
        add { _operation.Completed += value; }
        remove { _operation.Completed -= value; }
    }
}

请注意,在这种方法中,您不需要定义自定义事件参数类和事件处理程序委托。它们可以用 AsyncFunc 泛型类型代替:

OperationCompletedEventArgs -> ResultType
OperationCompletedEventHandler -> AsyncFuncCompletedEventHandler<ResultType>

对于更高级的场景,请访问 AsyncFunc 主页。有一些视频和示例。

于 2011-01-15T17:02:04.003 回答