欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-17 22:43:46
复制代码 代码如下:using system; using system.collections.generic; using system.linq; using sys...
复制代码 代码如下:

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

}

上一篇:

下一篇: