主线程 子线程 调用 ThreadId BeginInvoke调用和Invoke调用

BeginInvoke是异步线程执行 

class Program
    {
        static int TakeWhile() {
            int threadid = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("子线程ID:"+threadid);//每次运行不一样 测试为6
            Thread.Sleep(2000);
            return 5;
       
        }

        static void Main(string[] args)
        {
            int threadmain = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("主线程ID:" + threadmain);//每次运行不一样 测试为8
            Func<int> f1 = TakeWhile;
           IAsyncResult ar= f1.BeginInvoke(null,null);
            while(!ar.IsCompleted)
            {
                Console.Write("...");
               Thread.Sleep(1000);
               
            }
            int result=f1.EndInvoke(ar);
            Console.WriteLine(result);//5 EndInvoke会返回异步回调函数的值
            Console.WriteLine("结束");
            Console.Read();

        }

 

invoke 调用是同步执行 同一个线程执行

 class Program
    {
      public  static voidTakeWhile() {
            int threadid = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("子线程ID:"+threadid);//每次运行不一样 测试为1
            Thread.Sleep(2000);
        }

        static void Main(string[] args)
        {
            int threadmain = Thread.CurrentThread.ManagedThreadId;
           // Console.WriteLine(Thread.CurrentThread.GetHashCode());当前framework中线程这个值与ManagedThreadId一致
            Console.WriteLine("主线程ID:" + threadmain);//每次运行不一样 测试为1           
            typeof(ConsoleApplication2.Program).GetMethod("TakeWhile").Invoke(null, null);
            Console.WriteLine("结束");
            Console.Read();

        }


    }

posted on 2018-04-12 15:58  代码小王子来了  阅读(233)  评论(0编辑  收藏  举报