我正在用C#编写API,我想提供公开可用方法的同步和异步版本.例如,如果我有以下功能:
public int MyFunction(int x, int y) { // do something here System.Threading.Thread.Sleep(2000); return x * y; }
如何创建上述方法的异步版本(可能是BeginMyFunction和EndMyFunction)?是否有不同的方法来实现相同的结果,各种方法的好处是什么?
通用方法是使用delegate
:
IAsyncResult BeginMyFunction(AsyncCallback callback) { return BeginMyFunction(callback, null); } IAsyncResult BeginMyFunction(AsyncCallback callback, object context) { // Funcis just a delegate that matches the method signature, // It could be any matching delegate and not necessarily be *generic* // This generic solution does not rely on generics ;) return new Func (MyFunction).BeginInvoke(callback, context); } int EndMyFunction(IAsyncResult result) { return new Func (MyFunction).EndInvoke(result); }