Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C# 스레딩의 Join, Sleep 및 Abort 메서드

<시간/>

가입

표준 COM 및 SendMessage 펌핑을 계속 수행하면서 스레드가 종료될 때까지 호출 스레드를 차단합니다. 이 메서드에는 다른 오버로드된 형식이 있습니다.

수면

일정 시간 동안 스레드를 일시 중지합니다.

중단

Abort 메소드는 스레드를 파괴하는 데 사용됩니다.

스레딩에서 Join()의 예를 살펴보겠습니다 -

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

스레딩에서 abort() 및 sleep()의 예를 살펴보겠습니다.

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'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();
      }
   }
}