C#中一个异步回调的实例

来源:互联网 发布:visio绘制网络拓扑图 编辑:程序博客网 时间:2024/05/18 03:23
namespace 委托_异步_回调{    class Program    {        //创建委托,并实例化一个方法        public delegate string MyDelegate(object data);        private MyDelegate mydelegate = null;        static void Main(string[] args)        {            //开始异步执行            mydelegate =new MyDelegate(TestMethod);            IAsyncResult result = mydelegate.BeginInvoke("Thread Param", TestCallback, null);            //判断是否执行完成            Console.Write("请稍等");            while (!result.AsyncWaitHandle.WaitOne(100))            {                Console.Write(".");            }            Console.ReadLine();        }        //线程函数,即异步执行的程序        public string TestMethod(object data)        {            string datastr = data.ToString();            System.Threading.Thread.Sleep(1000);            return datastr;        }        //异步回调函数,异步执行完成以后需要返回的数据        public void TestCallback(IAsyncResult data)        {            //datastr,异步回调最终得到的数据,也就是异步执行程序执行完了以后的返回值            //data,异步回调的对象,也是传入回调函数的一个数据,可以用来和返回值进行相关操作            string datastr=mydelegate.EndInvoke(data);            Console.WriteLine("\n"+datastr);        }    }}
1 0
原创粉丝点击