栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

基于使用BeginInvoke,EndInvoke异步调用委托的实现代码

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于使用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 delegateMethod = new Func(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 method = (Func)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;
            }
        }
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/127276.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号