Join, Sleep and Abort methods in C# threads

WBOY
Release: 2023-09-15 11:01:09
forward
1606 people have browsed it

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();
      }
   }  
}
Copy after login

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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template