委托异步调用 C#

与世无争的帅哥 提交于 2019-12-16 21:16:52


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;           //AsyncResult需要此命名空间
using System.Threading;                        //Thread.Sleep(5000)需要此命名空间

namespace DelegateAsyncCall
{  
    public delegate int BinaryOp(int larg, int rarg);
    class Program
    {
        static void Main(string[] args)
        {
            BinaryOp b = new BinaryOp(Add);
            IAsyncResult ifR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), null);
            //Main Thread.. 模拟主线程所操作
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine("Main thread...");
            }
            Console.Read();
        }

        static int Add(int larg, int rarg)
        {
            try
            {
                int.Parse(larg.ToString());
                int.Parse(rarg.ToString());
            }
            catch
            {
                throw new ArgumentException("Integer arguments needed");
                return 0;
            }
            Thread.Sleep(5000);       //增加延时, shide
            return larg + rarg;
        }

        static void AddComplete(IAsyncResult iaR)
        {
            AsyncResult aR= (AsyncResult)iaR;
            BinaryOp b = (BinaryOp)aR.AsyncDelegate;
            Console.WriteLine("Adding results is {0}",b.EndInvoke (iaR));
            Console.Read();
        }
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!