English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
스레드 프로그램의 실행 경로로 정의됩니다. 각 스레드는 독특한 제어 흐름을 정의합니다.如果你的应用程序涉及到复杂的和耗时的操作,那么设置不同的线程执行路径往往是有益的,每个线程执行特定的工作。
스레드는가벼운 프로세스线程의 사용은 현대 운영체제에서 병행 프로그래밍의 구현에 일반적인 예입니다.线程 사용은 CPU 주기를 낭비하는 것을 절약하면서 애플리케이션의 효율성을 높입니다.
지금까지 작성한 프로그램은 애플리케이션의 실행 예제로서 단일 스레드로 한 과정을 실행하는 단일 과정입니다. 여러 가지 작업을 동시에 실행하려면, 더 작은 스레드로 나눌 수 있습니다.
스레드 생명주기는 System.Threading.Thread 클래스의 객체가 생성되는 순간부터, 스레드가 종료되거나 실행을 완료하는 순간까지 시작되고 끝납니다.
아래는 스레드 생명주기 중 다양한 상태를 나열합니다:
실행 전 상태:스레드 예제가 생성되었지만 Start 메서드가 호출되지 않은 상태.
준비 상태:스레드가 실행 준비가 되어 CPU 주기를 기다리는 상태.
실행 불가 상태:다음과 같은 상황에서 스레드는 실행할 수 없습니다:
Sleep 메서드가 호출된 상태
Wait 메서드가 호출된 상태
I/O 운영이 블록된 상태
사망 상태:스레드가 실행을 완료하거나 중지된 상태.
C#에서System.Threading.Thread 클래스는 스레드 작업을 위해 사용됩니다. 그것은 다중 스레드 애플리케이션에서 단일 스레드를 생성하고 접근할 수 있게 합니다. 프로세스에서 최초로 실행되는 스레드는주 스레드.
C# 프로그램이 실행될 때, 주 스레드는 자동으로 생성됩니다. Thread 클래스가 생성한 스레드는 주 스레드의 서브 스레드에 의해 호출됩니다. Thread 클래스의 CurrentThread 속성 접근 스레드.
아래의 프로그램은 주 스레드의 실행을 보여줍니다:
using System; using System.Threading; namespace MultithreadingApplication { class MainThreadProgram { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "MainThread"; Console.WriteLine("This is {0}", th.Name); Console.ReadKey(); } } }
위의 코드가 컴파일되고 실행될 때, 다음과 같은 결과가 생성됩니다:
This is MainThread
아래 표는 Thread 클래스에서 일반적으로 사용되는 속성:
속성 | 설명 |
---|---|
CurrentContext | 스레드가 현재 실행 중인 컨텍스트를 가져옵니다. |
CurrentCulture | 현재 스레드의 지역성을 가져오거나 설정합니다. |
CurrentPrincipal | 스레드의 현재 주체(롤 기반 보안에 대해)를 가져오거나 설정합니다. |
CurrentThread | 현재 실행 중인 스레드를 가져옵니다. |
CurrentUICulture | 실행 시간에 지역성 특정 자원을 찾기 위해 사용하는 현재 지역성을 가져오거나 설정합니다. |
ExecutionContext | ExecutionContext 객체를 얻어 현재 스레드에 대한 여러 가지 컨텍스트 정보를 포함하고 있습니다. |
IsAlive | 현재 스레드의 실행 상태를 얻습니다. |
IsBackground | 스레드가 백그라운드 스레드인지 여부를 얻거나 설정합니다. |
IsThreadPoolThread | 스레드가 관리된 스레드 풀에 속하는지 여부를 얻습니다. |
ManagedThreadId | 현재 관리된 스레드의 유일한 식별자를 얻습니다. |
Name | 스레드의 이름을 얻거나 설정합니다. |
Priority | 스레드의 스케줄링 우선순위를 얻거나 설정합니다. |
ThreadState | 현재 스레드의 상태를 포함하는 값을 얻습니다. |
아래 표는 Thread 클래스에서 일반적으로 사용되는 메서드:
순번 | 메서드 이름 & 설명 |
---|---|
1 | public void Abort() ThreadAbortException을 호출된 스레드에서 발생시키기 위해 이 메서드를 호출하여 이 스레드의 종료 과정을 시작합니다. 이 메서드를 호출하는 것은 일반적으로 스레드를 종료합니다. |
2 | public static LocalDataStoreSlot AllocateDataSlot() 모든 스레드에서 이름 지정되지 않은 데이터 슬롯을 할당합니다. 성능을 개선하기 위해 ThreadStaticAttribute 속성으로 표시된 필드를 사용하십시오. |
3 | public static LocalDataStoreSlot AllocateNamedDataSlot(
string name) 모든 스레드에서 이름 지정된 데이터 슬롯을 할당합니다. 성능을 개선하기 위해 ThreadStaticAttribute 속성으로 표시된 필드를 사용하십시오. |
4 | public static void BeginCriticalRegion() 알림: 주인이 코드 영역에 진입할 것입니다. 이 코드 영역 내에서 스레드가 중지되거나 미처리된 예외의 영향은 애플리케이션 도메인 내의 다른 작업에 위협이 될 수 있습니다. |
5 | public static void BeginThreadAffinity() 알림: 주인 주체 코드가 현재 물리 운영 체제 스레드의 식별자에 의존하는 명령을 실행할 것입니다. |
6 | public static void EndCriticalRegion() 알림: 주인이 코드 영역에 진입할 것입니다. 이 코드 영역 내에서 스레드가 중지되거나 미처리된 예외는 현재 작업에 영향을 미칩니다. |
7 | public static void EndThreadAffinity() 알림: 주인 주체 코드가 현재 물리 운영 체제 스레드의 식별자에 의존하는 명령을 완료했습니다. |
8 | public static void FreeNamedDataSlot(string name) 프로세스의 모든 스레드에서 이름과 슬롯 간의 연결을 제거합니다. 성능을 위해 ThreadStaticAttribute 속성으로 표기된 필드를 사용하도록 바꾸세요. |
9 | public static Object GetData(
LocalDataStoreSlot slot
) 현재 스레드의 현재 도메인에서 지정된 슬롯에서 값을 검색합니다. 성능을 위해 ThreadStaticAttribute 속성으로 표기된 필드를 사용하도록 바꾸세요. |
10 | public static AppDomain GetDomain() 현재 스레드가 실행 중인 현재 도메인을 반환합니다. |
11 | public static AppDomain GetDomainID() 고유한 응용 프로그램 도메인 식별자를 반환합니다. |
12 | public static LocalDataStoreSlot GetNamedDataSlot(
string name
) 이름이 지정된 데이터 슬롯을 찾습니다. 성능을 위해 ThreadStaticAttribute 속성으로 표기된 필드를 사용하도록 바꾸세요. |
13 | public void Interrupt() WaitSleepJoin 스레드 상태에 있는 스레드를 중지합니다. |
14 | public void Join() 표준 COM 및 SendMessage 메시지 펌프 처리를 계속하면서 호출된 스레드를 블록하여 특정 스레드가 종료될 때까지 대기합니다. 이 메서드는 다양한 오버로드 형식을 가집니다. |
15 | public static void MemoryBarrier() 메모리 접근을 동기화하는 방법은 다음과 같습니다: 현재 스레드의 프로세서가 명령어 재정렬을 수행할 때, MemoryBarrier 호출 이후의 메모리 접근을 MemoryBarrier 호출 이전의 메모리 접근으로 수행하지 마세요. |
16 | public static void ResetAbort() 현재 스레드에 요청된 Abort를 취소합니다. |
17 | public static void SetData(
LocalDataStoreSlot slot,
Object data
) 현재 실행 중인 스레드에서 이 스레드의 현재 도메인에 지정된 슬롯에서 데이터를 설정합니다. 성능을 위해 ThreadStaticAttribute 속성으로 표기된 필드를 사용하도록 바꾸세요. |
18 | public void Start() 스레드를 시작합니다。 |
19 | public static void Sleep(
int millisecondsTimeout
) pauses the thread for a period of time. |
20 | public static void SpinWait(
int iterations
) causes the thread to wait for the time defined by the iterations parameter. |
21 | public static byte VolatileRead(
ref byte address
) public static double VolatileRead( ref double address ) public static int VolatileRead( ref int address ) public static Object VolatileRead( ref Object address ) Reads the field value. The value is written by any processor of the computer, regardless of the number of processors or the state of the processor cache. This method has different overloads. Here are some of the forms. |
22 | public static void VolatileWrite(
ref byte address,
byte value
) public static void VolatileWrite( ref double address, double value ) public static void VolatileWrite( ref int address, int value ) public static void VolatileWrite( ref Object address, Object value ) Immediately writes a value to the field to make the value visible to all processors in the computer. This method has different overloads. Here are some of the forms. |
23 | public static bool Yield() causes the calling thread to execute another thread that is ready to run on the current processor. The operating system selects the thread to be executed. |
Threads are created by extending the Thread class. The extended Thread class calls Start() methods to start the execution of a child thread.
The following program demonstrates this concept:
using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); } 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(); } } }
위의 코드가 컴파일되고 실행될 때, 다음과 같은 결과가 생성됩니다:
Main에서: 자식 스레드를 생성합니다 자식 스레드 시작
The Thread class provides various methods for thread management.
The following example demonstrates sleep() method usage, used to pause a thread for a specific time.
using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); // thread pause 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(); } } }
위의 코드가 컴파일되고 실행될 때, 다음과 같은 결과가 생성됩니다:
Main에서: 자식 스레드를 생성합니다 자식 스레드 시작 Child Thread Paused for 5 seconds Child 스레드가 계속됩니다
Abort() Abort() 메서드는 스레드를 파괴하는 데 사용됩니다.
메서드를 통해 푸시합니다 threadabortexception 시간 중에 스레드를 중지합니다. 이 예외는 잡을 수 없습니다, 만약 finally 블록에서, 컨트롤이 전달됩니다 finally 블록.
아래의 프로그램은 이 점을 설명합니다:
using System; using System.Threading; namespace MultithreadingApplication { class ThreadCreationProgram { public static void CallToChildThread() { try { Console.WriteLine("Child thread starts"); // 카운팅까지 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(); // 메인 스레드를 일정 시간 정지합니다 Thread.Sleep(2000); // 현재 자식 스레드를 중지합니다 Console.WriteLine("In Main: Aborting the Child thread"); childThread.Abort(); Console.ReadKey(); } } }
위의 코드가 컴파일되고 실행될 때, 다음과 같은 결과가 생성됩니다:
Main에서: 자식 스레드를 생성합니다 자식 스레드 시작 0 1 2 Main에서: 자식 스레드를 중지합니다 Thread Abort 예외 Thread 예외를 잡을 수 없습니다