首页 > 编程 > C# > 正文

C#同步和异步调用方法实例

2020-01-24 03:04:44
字体:
来源:转载
供稿:网友

复制代码 代码如下:

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("********同步调用开始**********");
            int result = Add(1,2);
            Console.WriteLine("同步调用完毕,执行结果为:" + result);

            Console.WriteLine("********异步调用开始**********");
            SynAdd(1, 2, (r) => {
                Console.WriteLine("异步调用完毕,执行结果为:" + r);
            });
            Console.WriteLine("-------完毕!----------");
            Console.ReadLine();
        }

        /// <summary>
        /// 同步方法
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        static int Add(int a, int b)
        {
            Thread.Sleep(5000);
            return a + b;
        }

        /// <summary>
        /// 异步调用
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="callback">委托对象</param>
        static void SynAdd(int a, int b, Action<int> callback)
        {
            Func<int> func = () =>
            {
                Thread.Sleep(5000);
                return a+b;
            };//声明异步方法实现方式
            func.BeginInvoke((ar) =>
            {
                var result = func.EndInvoke(ar);//调用完毕执行的结果
                callback.Invoke(result);//委托执行,回传结果值
            }, null);
        }
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表