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

}

좋은 웹페이지 즐겨찾기