假设我有使用异步编程模型的代码,即它提供以下方法作为可以同步或异步使用的组:
public MethodResult Operation(<method params>);
public IAsyncResult BeginOperation(<method params>, AsyncCallback callback, object state);
public MethodResult EndOperation(IAsyncResult ar);
我想要做的是将此代码包装一个额外的层,将其转换为事件驱动的异步模型,如下所示:
public void OperationAsync(<method params>);
public event OperationCompletedEventHandler OperationCompleted;
public delegate void OperationCompletedEventHandler(object sender, OperationCompletedEventArgs e);
是否有人对如何完成此任务有任何指导(或指向此类指导的链接)?
答案 0 :(得分:2)
有关此问题的一些想法,请参阅"Async without the pain";提供的代码使用回调方法,但如果将它放在实例上,事件就很容易了。
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);
}
答案 1 :(得分:2)
您可以使用AsyncFunc库进行包装。
代码如下所示:
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主页。有一些视频和样本。