經過委託異步調用方法

 using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;異步

namespace 經過委託異步調用方法
{
    //委託聲明(函數簽名)
    delegate string MyMethodDelegate();ide

    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();spa

            //方式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.WriteLine(strEnd);
            Console.Read();
        }
    }
}對象

相關文章
相關標籤/搜索