使用BeginInvoke,EndInvoke非同步呼叫委託

來源:互聯網
上載者:User
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Console.WriteLine("Main ThreadId = " + Thread.CurrentThread.ManagedThreadId);            //給委託賦值            Func<long, long> delegateMethod = new Func<long, long>(CalcSum);            //非同步執行委託,這裡把委託本身作為asyncState對象傳進去,在回呼函數中需要使用委託的EndInvoke來獲得結果            delegateMethod.BeginInvoke(200, DoneCallback, delegateMethod);            //非同步執行委託,拋出異常            delegateMethod.BeginInvoke(10000000000, DoneCallback, delegateMethod);            Console.ReadLine();        }        //委託回呼函數        static void DoneCallback(IAsyncResult asyncResult)        {            //到這兒委託已經在非同步線程中執行完畢            Console.WriteLine("DoneCallback ThreadId = " + Thread.CurrentThread.ManagedThreadId);            Func<long, long> method = (Func<long, long>)asyncResult.AsyncState;            //委託執行的異常會在EndInvoke時拋出來            try {                //使用BeginInvoke時傳入委託的EndInvoke獲得計算結果,這時候計算結果已經出來了,有異常的話也在這兒拋出來                long sum = method.EndInvoke(asyncResult);                Console.WriteLine("sum = {0}",sum);            }            catch (OverflowException)            {                Console.WriteLine("運算溢出了");            }        }        //委託方法        static long CalcSum(long topLimit)        {            //委託在另一個線程中開始執行            Console.WriteLine("Calc ThreadId = " + Thread.CurrentThread.ManagedThreadId);            checked            {                long result = 0;                for (long i = 0; i < topLimit; i++)                {                    result += i;                }                return result;            }        }    }}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.