c#的BeginInvoke和EndInvoke使用demo

BeginInvoke方法可使用線程異步地執行委託所指向的方法。而後經過EndInvoke方法得到方法的返回值(EndInvoke方法的返回值就是被調用方法的返回值),或是肯定方法已經被成功調用。dom

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);
        }
    }


}
相關文章
相關標籤/搜索