非同步委託的幾種實現方式

來源:互聯網
上載者:User

        最近,在看C#進階編程第七版的線程、任務、同步這一章,因為現在多線程編程,非同步編程對構建響應靈敏的介面以及構建高延展性的服務應用是多麼重要。現在就來記錄一下自己今天學習的成果。

      建立線程的一種簡單方式是定義一個委託,並非同步呼叫它。總結一下,非同步呼叫委託的方式有如下3種:

      1.投票

     //定義一個需要一定的時間才能執行完畢的方法

     static int TakesAWhile(int data, int ms)
        {
            Console.WriteLine("TakesAWhile started");
            Thread.Sleep(ms);
            Console.WriteLine("TakesAWhile completed");
            return ++data;
        }

 

      //要從委託中調用這個方法,必須定義一個有相同參數和傳回型別的委託

       public delegate int TakesAWhileDelegate(int data,int ms);

 

    //所建立的delegate類提供了BeginInvoke()方法,在該方法中,可以傳遞用委託定義的輸入的函數。BeginInvoke()方法總是有AsyncCallback和object類型的兩個額外參數。BeginInvoke()方法的傳回型別是IAsyncResult。通過IAsyncResult,可以獲得該委託的相關資訊,並通過IsCompleted屬性驗證該委託是否完成了任務。只要委託沒有完成其任務,程式的主線程就繼續執行while迴圈。

       static void Main(string[] args)
        {
            TakesAWhileDelegate d1 = TakesAWhile;
            //使用投票方式調用非同步委託
            IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
            while (!ar.IsCompleted)
            {
                //doing something else in the main thread
                Console.Write(".");
                Thread.Sleep(50);
            }
            int result = d1.EndInvoke(ar);
           Console.WriteLine("result:{0}", result);

       }

 

 

    2.等待控制代碼

   

 static void Main(string[] args)
        {
            TakesAWhileDelegate d1 = TakesAWhile;
            //使用等待控制代碼的方式調用非同步委託
            while (true)
            {
                Console.Write(".");
                if (ar.AsyncWaitHandle.WaitOne(50, false))
                {
                   Console.WriteLine("Can get the result now");
                   break;
                }
                int result = d1.EndInvoke(ar);
                Console.WriteLine("result:{0}", result);
            }      

        }

    3.使用非同步回調

     static void Main(string[] args)
        {

          

           TakesAWhileDelegate d1 = TakesAWhile;
            d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1);
            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }       

         }

 

       static void TakesAWhileCompleted(IAsyncResult ar)
        {
           if (ar == null) throw new ArgumentException("ar");
            TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate;
            Trace.Assert(d1 != null, "Invalid object type");
            int result = d1.EndInvoke(ar);
            Console.WriteLine("result:{0}", result);
         }

 

 //使用非同步回調-lamda運算式的方式調用委託
static void Main(string[] args)
        {

             d1.BeginInvoke(1, 3000, ar =>
            {
                int result = d1.EndInvoke(ar);
                Console.WriteLine("result:{0}", result);
            }, null);
            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
               Thread.Sleep(50);
            }                

}

 

 

 

 

 

  

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.