使用BeginInvoke,EndInvoke異步調用委托


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;
            }
        }
    }

}

  


免責聲明!

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



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