1.初探

1.线程需要通过委托去开启。

 private static void Main(string[] args)
        {
            //通过委托开启线程
            Func<int, string, int> a = Test;
            //开启新的线程去执行a所引用的函数
            //IAsyncResult 取得当前线程状态
            IAsyncResult ar = a.BeginInvoke(100, "maning", null, null);

            //可以认为线程是同时执行的(异步执行)
            Console.WriteLine("main");
            while(ar.IsCompleted == false)
            {
                Console.Write(".");
                Thread.Sleep(10);
            }
            int res = a.EndInvoke(ar);
            Console.WriteLine(res);

       bool isEnd = ar.AsyncWaitHandle.WaitOne(1000);//等待1000毫秒,1000毫秒结束,返回true,没结束返回false
            if(isEnd)
            {
                int res = a.EndInvoke(ar);
                Console.WriteLine(res);
            }
            Console.ReadKey(); Console.ReadKey(); }
private static int Test(int i, string name) { Console.WriteLine("Test" + i + " " + name); //当前线程暂停100ms Thread.Sleep(100); return 100; }
IAsyncResult ar = a.BeginInvoke(100, "maning", null, null);
ar储存当前线程运行状态


int res = a.EndInvoke(ar);
res 取得当前线程运行结果。

Thread.Sleep(100)当前线程暂停100ms
ar.AsyncWaitHandle.WaitOne(1000)

等待1000毫秒,1000毫秒结束,返回true,没结束返回false,只会等待1000ms。如果执行700ms,等待700ms,若超过1000ms,只会等待1000ms。
 

 

posted @ 2017-05-27 14:20  C#小白鼠  阅读(137)  评论(0编辑  收藏  举报