在C#中提供方法的同步和异步版本

ade*_*825 4 .net c# asynchronous

我正在用C#编写API,我想提供公开可用方法的同步和异步版本.例如,如果我有以下功能:

public int MyFunction(int x, int y)
{
   // do something here
   System.Threading.Thread.Sleep(2000);
   return  x * y;

}
Run Code Online (Sandbox Code Playgroud)

如何创建上述方法的异步版本(可能是BeginMyFunction和EndMyFunction)?是否有不同的方法来实现相同的结果,各种方法的好处是什么?

Meh*_*ari 7

通用方法是使用delegate:

IAsyncResult BeginMyFunction(AsyncCallback callback)
{
    return BeginMyFunction(callback, null);
}

IAsyncResult BeginMyFunction(AsyncCallback callback, object context)
{
    // Func<int> is 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<int>(MyFunction).BeginInvoke(callback, context);
}

int EndMyFunction(IAsyncResult result)
{
    return new Func<int>(MyFunction).EndInvoke(result);
}
Run Code Online (Sandbox Code Playgroud)