C# Thread.Join();Thread.Abort();

Join() 等待当前线程运行完成后,才继续执行主线程后续代码;

Abort() 结束当前线程,继续执行主线程后续代码;

 

 

 

 Thread.Join();

static void Main(string[] args)
        {
            Console.WriteLine("Starting program...");
            Thread t = new Thread(PrintNumbersWithDelay);
            t.Start();
            t.Join();//在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止。
            Console.WriteLine("Thread completed");
            Console.Read();
        }

        static void PrintNumbersWithDelay()
        {
            Console.WriteLine("Starting...");
            for (int i = 1; i < 10; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine(i);
            }
        }

 

 

Thread.Abort();//

        static void Main(string[] args)
        {
            Console.WriteLine("Starting program...");
            Thread t = new Thread(PrintNumbersWithDelay);
            t.Start();
            Thread.Sleep(TimeSpan.FromSeconds(6));
            t.Abort();//在调用此方法的线程上引发 System.Threading.ThreadAbortException,以开始终止此线程的过程。调用此方法通常会终止线程。
            Console.WriteLine("A thread has been aborted");
            Console.Read();
        }

        static void PrintNumbersWithDelay()
        {
            Console.WriteLine("Starting...");
            for (int i = 1; i < 10; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine(i);
            }
        }

 

 

/

posted @ 2019-07-13 09:52  蓝雨冰城  阅读(1256)  评论(0编辑  收藏  举报