1. 程式人生 > 實用技巧 >.NET 非同步 /Task

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

        }


    }





}