Implementation code based on the use of BeginInvoke EndInvoke asynchronous call delegate

  • 2020-05-10 18:45:52
  • OfStack


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); 
            // Assign a value to the delegate  
            Func<long, long> delegateMethod = new Func<long, long>(CalcSum); 
            // Asynchronous execution delegate , I'm going to take the delegate itself asyncState Object is passed in, and the delegate is used in the callback function EndInvoke To get results  
            delegateMethod.BeginInvoke(200, DoneCallback, delegateMethod); 
            // Asynchronous execution delegate , An exception is thrown  
            delegateMethod.BeginInvoke(10000000000, DoneCallback, delegateMethod); 
            Console.ReadLine(); 
        } 

        // Delegate callback function  
        static void DoneCallback(IAsyncResult asyncResult) 
        { 
            // Here the delegate has finished executing in the asynchronous thread  
            Console.WriteLine("DoneCallback ThreadId = " + Thread.CurrentThread.ManagedThreadId); 

            Func<long, long> method = (Func<long, long>)asyncResult.AsyncState; 
            // The exception executed by the delegate will be EndInvoke When thrown out  
            try { 
                // use BeginInvoke Is passed to the delegate EndInvoke You get the result, you get the result, you get the result, you get the exception right here  
                long sum = method.EndInvoke(asyncResult); 
                Console.WriteLine("sum = {0}",sum); 
            } 
            catch (OverflowException) 
            { 
                Console.WriteLine(" Arithmetic overflow "); 
            } 
        } 

        // The delegate  
        static long CalcSum(long topLimit) 
        { 
            // Commissioned in the other 1 Start execution in 1 thread  
            Console.WriteLine("Calc ThreadId = " + Thread.CurrentThread.ManagedThreadId); 
            checked
            { 
                long result = 0; 
                for (long i = 0; i < topLimit; i++) 
                { 
                    result += i; 
                } 
                return result; 
            } 
        } 
    } 

}

Related articles: