提供了方法在C#中同步和异步版本 [英] Providing Synchronous and Asynchronous Versions of Method in C#

查看:106
本文介绍了提供了方法在C#中同步和异步版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing an API in C# and I want to provide both synchronous and asynchronous versions of the publicly available methods. For example, if I have the following function:

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

}

我怎么能创造上述方法(也许BeginMyFunction和EndMyFunction)的异步版本?是否有不同的方法来达到同样的效果,什么是各种方法的好处是什么?

how can I create an asynchronous version of the above method (perhaps BeginMyFunction and EndMyFunction)? Are there different ways to achieve the same result, and what are the benefits of the various approaches?

推荐答案

普通的方法是使用代理

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);
}

这篇关于提供了方法在C#中同步和异步版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆