程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Part 92 Significance of Thread Join and Thread IsAlive functions,threadisalive

Part 92 Significance of Thread Join and Thread IsAlive functions,threadisalive

編輯:C#入門知識

Part 92 Significance of Thread Join and Thread IsAlive functions,threadisalive


Thread.Join & Thread.IsAlive functions

Join blocks the current thread and makes it wait until the thread on which Join method is invoked completes.Join method also has a overload where we can specify the timeout. If we don't specify the timeout the calling thread waits indefinitely(無限期地), until the thread on which Join() is invoked completes. This overloaded Join(int millisecondesTimeout) method returns boolean. True if the thread has terminated(終止) otherwise false.

Join is particularly(特別地) useful when we need to wait and collect result from a thread execution or if we need to do some clean-up after the thread has completed.

IsAlive returns boolean. True if the thread is still executing otherwise false.

public static void Main(string[] args)
        {
            Console.WriteLine("main start");
            Thread t1 = new Thread(ThreadFunction1);
            t1.Start();
            Thread t2 = new Thread(ThreadFunction2);
            t2.Start();
            if(t1.Join(1000))
            {
                Console.WriteLine("threadfunction1 end");
            }
            else
            {
                Console.WriteLine("threadfunction1 still working");
            }
            if(t1.IsAlive)
            {
                for (int i = 1; i < 10; i++)
                {
                    Console.WriteLine("threadfunction1 still working...");
                    Thread.Sleep(500);                    
                }
            }
            Console.WriteLine("main end");
        }

        public static void ThreadFunction1()
        {
            Console.WriteLine("threadfunction1 start");
            Thread.Sleep(5000);
            Console.WriteLine("threadfunction1 end");
        }

        public static void ThreadFunction2()
        {
            Console.WriteLine("threadfunction2 start");
        }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved