Home  >  Article  >  Backend Development  >  Join, Sleep and Abort methods in C# threads

Join, Sleep and Abort methods in C# threads

WBOY
WBOYforward
2023-09-15 11:01:091607browse

C# 线程中的 Join、Sleep 和 Abort 方法

Join

Blocks the calling thread until the thread terminates, while continuing standard COM and SendMessage pumping. This method has different overloaded forms.

Sleep

Pauses the thread for a period of time.

Abort

The Abort method is used to destroy the thread.

Let us see an example of Join() in thread -

Example

using System;
using System.Diagnostics;
using System.Threading;
namespace Sample {
   class Demo {
      static void Run() {
         for (int i = 0; i < 2; i++)
         Console.Write("Sample text!");
      }
      static void Main(string[] args) {
         Thread t = new Thread(Run);
         t.Start();
         t.Join();
         Console.WriteLine("Thread terminated!");
         Console.Read();
      }
   }  
}

Let us see an example of abort() and sleep() in thread.

Example

using System;
using System.Threading;
namespace Demo {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         try {
            Console.WriteLine("Child thread starts");
            // do some work, like counting to 10
            for (int counter = 0; counter <= 10; counter++) {
               Thread.Sleep(500);
               Console.WriteLine(counter);
            }
            Console.WriteLine("Child Thread Completed");
         } catch (ThreadAbortException e) {
            Console.WriteLine("Thread Abort Exception");
         } finally {
            Console.WriteLine("Couldn&#39;t catch the Thread Exception");
         }
      }
      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         //stop the main thread for some time
         Thread.Sleep(2000);
         //now abort the child
         Console.WriteLine("In Main: Aborting the Child thread");
         childThread.Abort();
         Console.ReadKey();
      }
   }
}

The above is the detailed content of Join, Sleep and Abort methods in C# threads. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete