c# async,await, 委托函數


1.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.委托函數

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

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的使用一樣,只是缺少了返回類型,直接調用委托函數。

Public void Add(int param1,int param2)
{
  MessageBox.show((param1+param2).ToString());
}
//遇到此類的委托函數調用,那我們就可以直接用Action了:
Action<int,int> math=Add;
math(3,4);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM