当前位置:编程学习 > C#/ASP.NET >>

C#异步委托的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;


namespace 异步委托
{
    /// <summary>
    /// 说明异步委托调用时会产生一个新的线程,不会阻塞主线程,
    /// 前提是使用回调函数,而不是直接使用委托的.endinvoke方法获取结果
    /// </summary>
    class Program
    {
        public delegate int AddDel(int x, int y);


        static void Main(string[] args)
        {
            //定义委托
            AddDel addDel = new AddDel(AddFunc);
            Console.WriteLine("主线程开始执行...{0}",Thread.CurrentThread.ManagedThreadId);
            //开始异步调用委托
            addDel.BeginInvoke(2, 3, Callback, 2);  //第三个参数回调函数,第四个参数,额外参数
            Console.WriteLine("主线程执行完毕!");
            Console.ReadKey();
        }


        static int AddFunc(int x, int y)
        {
            Console.WriteLine("子线程在执行:{0}",Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(3000);
            return x + y;
        }


        static void Callback(IAsyncResult ar)
        {
            AsyncResult asy = (AsyncResult)ar;
            //获取代理信息
            AddDel addDel = (AddDel)asy.AsyncDelegate;
            //获取返回结果
            int result = addDel.EndInvoke(ar);
            //获取额外参数
            int otherData = (int)asy.AsyncState;


            Console.WriteLine("子线程执行完毕!{0},执行结果:{1},额外参数:{2}",Thread.CurrentThread.ManagedThreadId
                                    ,result,otherData);


        }
    }
}

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,