C#에서 System.Threading.Thread 클래스는 스레드 작업에 사용됩니다. 다중 스레드 응용 프로그램에서 개별 스레드를 만들고 액세스할 수 있습니다. 프로세스에서 가장 먼저 실행되는 스레드를 메인 스레드라고 합니다.
C# 프로그램이 실행을 시작하면 기본 스레드가 자동으로 생성됩니다. Thread 클래스를 사용하여 생성된 스레드를 메인 스레드의 자식 스레드라고 합니다.
다음은 C#에서 스레드를 생성하는 방법을 보여주는 예입니다 -
using System;
using System.Threading;
namespace Demo {
class Program {
static void Main(string[] args) {
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
} 다음은 C#에서 스레드를 관리하는 방법을 보여주는 또 다른 예입니다 -
예시
using System;
using System.Threading;
namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
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();
Console.ReadKey();
}
}
} 출력
In Main: Creating the Child thread Child thread starts Child Thread Paused for 5 seconds Child thread resumes