.NET 异步 /Task

老版本的写法经常是以BeginXXX, EndXXX, 或者xx.xxxAsycn(........)

新的支持 async异步关键字配合Task可读性和易用性比老板好多了。

新旧例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Globalization;
using System.Net.Http.Headers;
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            TestClass class1 = new TestClass();
            class1.TestOldAsycn();
            class1.TestNewAsycn();
            Console.ReadLine();
        }
    }

    public class TestClass
    {

        private delegate long AddDel(int i, int j);
        public void TestOldAsycn()
        {

            AddDel del = Add;
            IAsyncResult ar = del.BeginInvoke(2, 3, MyCallBack, del);//参数里面的del 是用于残敌给回调函数调用,参看回调函数方法里的代码: ar.AsyncState as AddDel;
                                                                     //var result  del.EndInvoke(ar);//获取结果,会阻塞线程
            Console.WriteLine("Main contine .......");

        }
        private long Add(int i, int j)
        {
            Console.WriteLine("begin wait 5 sec---------------");
            System.Threading.Thread.Sleep(5000);
            return i + j;
        }
        /// <summary>
        /// callback 获得结果回到函数,beginXXX..里的任务执行完成后才会调用这个
        /// </summary>
        /// <param name="ar"></param>
        private void MyCallBack(IAsyncResult ar)
        {
            var d = ar.AsyncState as AddDel;//ar.AsyncState 是bingXXX里的Object
            var result = (d.EndInvoke(ar));//执行EndXXX获得结果
            Console.WriteLine("result:" + result);
        }


        //--------------新的.net更方便的Task/Asyc/Await语法----------------------------------------

        public async Task TestNewAsycn()
        {

            var result = await AddNew(2, 3);    //  OR AddNew(2,3);
            Console.WriteLine("new asycn result:" + result);
        }

        private async Task<long> AddNew(int i, int j)
        {
            Console.WriteLine("begin wait 5 sec---------------");
            System.Threading.Thread.Sleep(5000);
            return await Task.FromResult(i + j);

        }


    }





}

  

原文地址:https://www.cnblogs.com/wgscd/p/13475113.html