c# async,await, 委託函數

1.c#的異步實現,以前代碼編寫大都開幾個線程。c#

現能夠使用「async+await」方式實現異步(具體不詳細介紹,暫且止在會用,僅僅是c#更新史上一個工具):異步

        static void Main(string[] args)
        {
            method1();
            method2();//不會等待method1執行結束,再執行method2
            Console.ReadKey();
        }//結果輸出是"method 1"和"method 2"字符串交替出現,但不會嚴格按照1:1交替出現

        private static async Task method1()//必須使用task或task<T>作返回
        {
            await Task.Run(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine("method 1");
                }
            });

        }

        private static void method2()
        {
            for (int i = 0; i < 25; i++)
            {
                Console.WriteLine("method 2");
            }
        }

  2.委託函數async

  舊的使用方法:須要先定義委託類型,而後定義一個符合委託類型簽名的函數,
在調用前,需聲明並建立委託對象,將指定函數與委託進行關聯。函數

public delegate int Math(int param1,int param2);定義委託類型
Public int Add(int param1,int param2)//定義同簽名函數
{
  Return param1+param2;
}
Math math;//聲明委託
math=new Math(Add);建立委託對象,與指定進行關聯
math(3,4);//調用委託函數

  如今能夠使用內置委託類型:工具

Func<int,int,int> math=Add;//指定委託對象並關聯函數
math(3,4);//調用委託函數

  Action委託具備Action<T>、Action<T1,T2>、Action<T1,T2,T3>……Action<T1,……T16>多達16個的重載,其中傳入參數均採用泛型中的類型參數T,涵蓋了幾乎全部可能存在的無返回值的委託類型。Func則具備Func<TResult>、Func<T,Tresult>、Func<T1,T2,T3……,Tresult>17種類型重載,T1……T16爲出入參數,Tresult爲返回類型。線程

 

       既然是委託類型,也一樣能夠與匿名函數、或者採用Lambda表達式結合使用:對象

匿名函數:
Func<int,int,int> math=delegate(int param1,int param2)
{
  Return param1+param2;
}
Lambda:
Func<int,int,int> math=(param1,param2)=>
{
  Return param1+param2;
}

  Action的使用如同上面Func的使用同樣,只是缺乏了返回類型,直接調用委託函數。blog

Public void Add(int param1,int param2)
{
  MessageBox.show((param1+param2).ToString());
}
//遇到此類的委託函數調用,那咱們就能夠直接用Action了:
Action<int,int> math=Add;
math(3,4);
相關文章
相關標籤/搜索