欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#方法转异步例子

程序员文章站 2022-05-07 14:09:45
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ... ......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 亚信电子商务
{


    public class Program2
    {

        public static void Main(string[] args)
        {

            Console.WriteLine("主线程1");

            AsyncTest.ToAsync(()=> {

                Thread.Sleep(3000);

                Console.WriteLine("让我用新的线程执行吧,主线程你做你的事吧");

            }, () => { Console.WriteLine("回调"); });


            AsyncTest.ToAsync<string>(() => {

                Thread.Sleep(1000);
                return "女猪脚和男猪脚结婚了";

            }, p => { Console.WriteLine("回调结果:"+ p); });


            Console.WriteLine("主线程2");

            Console.ReadLine();
        }

    }



    /// <summary>
    /// 将一个普通方法转为异步方法
    /// </summary>
    public class AsyncTest
    {
        /// <summary>
        /// 把一个普通无参,无返回值的方法转为异步方法
        /// </summary>
        /// <param name="srcAction">要转的方法</param>
        /// <param name="callBack">回调方法</param>
        public static async Task ToAsync(Action srcAction,Action callBack)
        {
            //定义一个异步无返回值的方法,下面写法可能有点绕
            Func<Task> task = () =>
            {
                return Task.Run(() =>
                {
                    srcAction();

                });
            };
            await task();
            if (callBack != null)
            {
                callBack();
            }
        }

        /// <summary>
        /// 把一个无参有返回值的方法转为异步方法
        /// </summary>
        /// <typeparam name="T">泛型模板类型</typeparam>
        /// <param name="srcFunc">被转的源方法</param>
        /// <param name="callBack">回调</param>
        public static async Task ToAsync<T>(Func<T> srcFunc, Action<T> callBack)
        {

            Func<Task<T>> task = () => {
                return Task<T>.Run(() => {

                    return srcFunc();
                });
            };

            var result = await task();
            if (callBack != null)
            {
                callBack(result);
            }

        }



    }
}