天天看點

通過委托異步調用方法

 using System;

using System.Threading;

using System.Runtime.Remoting.Messaging;

namespace 通過委托異步調用方法

{

    //委托聲明(函數簽名)

    delegate string MyMethodDelegate();

    class MyClass

    {

        //要調用的動态方法

        public string MyMethod1()

        {

            return "Hello Word1";

        }

        //要調用的靜态方法

        public static string MyMethod2()

            return "Hello Word2";

    }

    class Class1

        /**/

        /// <summary>

        /// 應用程式的主入口點。

        /// </summary>

        [STAThread]

        static void Main(string[] args)

            MyClass myClass = new MyClass();

            //方式1:  聲明委托,調用MyMethod1

            MyMethodDelegate d = new MyMethodDelegate(myClass.MyMethod1);

            string strEnd = d();

            Console.WriteLine(strEnd);

            //方式2:  聲明委托,調用MyMethod2 (使用AsyncResult對象調用)

            d = new MyMethodDelegate(MyClass.MyMethod2); //定義一個委托可以供多個方法使用     

            AsyncResult myResult;   //此類封閉異步委托異步調用的結果,通過AsyncResult得到結果.

            myResult = (AsyncResult)d.BeginInvoke(null, null);        //開始調用

            while (!myResult.IsCompleted)  //判斷線程是否執行完成

            {

                Console.WriteLine("正在異步執行MyMethod2 ..");

            }

            Console.WriteLine("方法MyMethod2執行完成!");

            strEnd = d.EndInvoke(myResult);      //等待委托調用的方法完成,并傳回結果 

            Console.Read();

}

繼續閱讀