弹指一挥间

好好做事,学习待人 (大数据分析/.NET/JAVA)技术交流QQ:860280456; .NET/JAVA技术交流群:192028174

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

通用异步执行程序的方法,包括回调函数返回值..

IAsyncResult BeginInvoke EndInvoke

 
        #region 异步执行程序
 
        public void btnExecAsync(object sender, EventArgs e)
        {
            //给委托赋值
            _delegateMethod1 = DoSomeThing;// new DelegateMethod(DoSomeThing);
            //异步执行委托,这里把委托本身作为asyncState对象传进去,在回调函数中需要使用委托的EndInvoke来获得结果
            _delegateMethod1.BeginInvoke(DoneCallback, _delegateMethod1);
            for (int i = 0; i < 10000; i++)
            {
                //A部分
                //A和B部分是并行执行的,相互之间无影响
            }
        }
 
        private DelegateMethod _delegateMethod1;//实例化委托
        public delegate bool DelegateMethod();//声明委托
 
        /// <summary>
        /// 委托回调函数
        /// </summary>
        void DoneCallback(IAsyncResult asyncResult)
        {
            //到这儿委托(B部分)已经在异步线程中执行完毕
 
            //委托执行的异常会在EndInvoke时抛出来 
            try
            {
                //使用BeginInvoke时传入委托的EndInvoke获得执行结果,这时候执行结果已经出来了,有异常的话也在这儿抛出来
                bool result = _delegateMethod1.EndInvoke(asyncResult);
            }
            catch (OutOfMemoryException) // (OverflowException)
            {
                //MessageBox.Show("异常!")
            }
        }
 
        /// <summary>
        /// 委托方法 异步执行
        /// </summary> 
        bool DoSomeThing()
        {
            //B部分  委托在另一个线程中开始执行 
            for (int i = 0; i < 10000; i++)
            {
 
            }
            return true;
        }
 
        #endregion

 

单独执行一个异步方法的简洁调用:(这种方式的回调函数的返回值可以用全局变量来接收..)

private void AsyncMethod()
    {
        //定义一个与方法声明相同的委托来异步执行方法
        Func<int> delegate1 = () =>
        {
            //为方便调试看到效果,增加一个耗时的计算任务
            int sum = 0;
            for (int i = 0; i < 10000; i++)
            {
                sum += i;
            }
            return sum;
        };
 
        delegate1.BeginInvoke(state =>
       {
           int sum = delegate1.EndInvoke(state);
           Console.WriteLine("使用委托异步执行方法,结果为:{0}", sum.ToString());
           for (int i = 0; i < 10000; i++)
           {
               //为方便调试看到效果,增加一个耗时的计算任务
           }
       }, null);
    }

 

 

 

参考查阅的代码:

使用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 on 2013-03-25 23:56  v.e.n.u.s  阅读(1355)  评论(1编辑  收藏  举报