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

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

相关文章: