views:

303

answers:

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?

A: 

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);
}
Marc Gravell
(I would add an example, but train going out of coverage)
Marc Gravell
Interesting - this code style looks very similar to the Task Parallel Library.
David
Back in reception briefly... in the signature at least, it isn't far off how F# works under the hood, so I expect there will be similarities.
Marc Gravell