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

  

posted @   玉开  阅读(5564)  评论(4编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2009-05-06 使用open flash chart的BarGlass时遇到的问题
2008-05-06 c# 统计方法执行时间,计算缓存读取数据方法的命中率
点击右上角即可分享
微信分享提示