c#的BeginInvoke和EndInvoke使用demo

BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        private delegate int NewTaskDelegate(int ms,string msg);
        private static int newTask(int ms, string msg)
        {
            Console.WriteLine("任务开始");
            Thread.Sleep(ms);
            Random random = new Random();
            int n = random.Next(10000);
            Console.WriteLine("任务完成" + msg);
            return n;
        }
        static void Main(string[] args)
        {
            AsyncCallback asyncCallback = new AsyncCallback(MyAsyncCallback);
            NewTaskDelegate task = new NewTaskDelegate(newTask);
            IAsyncResult asyncResult = task.BeginInvoke(2000,"fk", asyncCallback, task);

            // EndInvoke方法将被阻塞2秒   
            //int result = task.EndInvoke(asyncResult);
            //Console.WriteLine(result);
            Console.ReadLine();
        }
        public static void MyAsyncCallback(IAsyncResult iar)
        {
            int str;
            NewTaskDelegate dlgt = (NewTaskDelegate)iar.AsyncState;
            str = dlgt.EndInvoke(iar);
            Console.WriteLine("the Delegate call returned string:{0}", str);
        }
    }


}

  

posted on 2017-05-17 18:34  狼来了  阅读(296)  评论(0编辑  收藏  举报