>  기사  >  백엔드 개발  >  C# 스레드

C# 스레드

王林
王林원래의
2024-09-03 15:25:25288검색

다음 문서에서는 C# 스레드에 대한 개요를 제공합니다. 프로그램의 실행 경로는 스레드로 정의되며, 각 스레드별로 고유한 제어 흐름이 정의됩니다. 애플리케이션이 복잡하고 시간이 많이 걸리는 작업으로 구성되어 있는 경우 각 스레드가 특정 작업을 담당하는 경우 실행 경로나 스레드를 다르게 설정해야 합니다. 이러한 스레드 프로세스는 경량화되고 동시 프로그래밍을 구현하는 최신 운영 체제는 스레드를 사용하는 사례 중 하나이며 스레드를 사용함으로써 중앙 처리 장치의 사이클 낭비를 줄이고 응용 프로그램의 효율성을 높입니다.

구문:

public sealed class Thread: System.Runtime.ConstrainedExecution.CriticalFinalizerObject

C# 스레드 클래스 작업

스레드의 생명주기가 시작될 때 System.Threading.Thread 클래스의 객체가 생성되는 시간입니다. 스레드 종료 또는 스레드 실행 완료가 발생하면 스레드가 생성되어 종료됩니다.

스레드의 수명 주기에는 여러 상태가 있습니다.

1. 시작되지 않은 상태: 이 상태는 시작 메소드가 호출되지 않고 스레드의 인스턴스가 생성될 때마다 발생하는 상황입니다.

2. 준비 상태: 스레드가 모두 실행되도록 설정되어 중앙 처리 장치의 주기를 기다리는 상태입니다.

3. 실행 불가능 상태: 이 상태는 다음과 같은 경우 스레드를 실행할 수 없는 상황입니다.

  • Sleep 메소드 호출이 있었습니다.
  • Wait 메소드 호출이 있었습니다.
  • 입/출력 작업으로 인해 차단이 발생했습니다.

4. The dead State: 이 상태는 스레드의 실행이 완료되었거나, 스레드의 실행이 중단된 상황입니다.

  • C#에서 스레드 작업을 하려면 System.Threading.Thread 클래스를 사용해야 합니다.
  • 멀티스레드 애플리케이션으로 작업하는 동안 C#의 System.Threading.Thread 클래스를 사용하여 개별 스레드를 생성하고 액세스할 수 있습니다.
  • 전체 프로세스에서 가장 먼저 실행되는 스레드를 메인 스레드라고 합니다.
  • C# 프로그램 실행이 시작되면 자동으로 메인 스레드가 생성됩니다.
  • Thread의 클래스를 이용하여 생성된 스레드를 메인 스레드의 자식 스레드라고 합니다.
  • Thread 클래스의 CurrentThread 속성은 스레드에 액세스하는 데 사용됩니다.

아래 프로그램은 메인 스레드의 실행을 보여줍니다.

코드:

using System;
using System.Threading;
//a namespace called multithreading is created
namespace Multithreading
{
//a class called mainthread is created under multithreading namespace
class MainThread
{
//main method is called
static void Main(string[] args)
{
//an instance of the thread class is created
Thread thr = Thread.CurrentThread;
//Name method of thread class is accessed using the instance of the thread class
thr.Name = "Thread Class";
//the content is displayed as the output
Console.WriteLine("Welcome to {0}", thr.Name);
Console.ReadKey();
}
}
}

출력:

C# 스레드

위 프로그램에서는 멀티스레딩이라는 네임스페이스가 생성됩니다. 그런 다음 멀티스레딩 네임스페이스 아래에 mainthread라는 클래스가 생성됩니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 스레드 클래스의 인스턴스가 생성됩니다. 그런 다음 스레드 클래스의 인스턴스를 사용하여 스레드 클래스의 Name 메서드에 액세스합니다. 마지막으로 화면에 출력이 표시됩니다.

스레드 클래스의 방식

아래에는 스레드 클래스의 여러 메서드가 나와 있습니다.

1. 중단()

스레드에서 Abort() 메서드가 호출될 때마다 ThreadAbortException이 발생하고 스레드 종료 프로세스가 시작됩니다. 이 메소드를 호출하면 스레드 종료가 발생합니다.

예: 

코드:

using System;
using System.Threading;
class ExThread
{
public void thr()
{
for (int y = 0; y < 3; y++)
{
Console.WriteLine(y);
}
}
}
class Example
{
public static void Main()
{
ExThread ob = new ExThread();
Thread th = new Thread(new ThreadStart(ob.thr));
th.Start();
Console.WriteLine("Aborting the thread");
th.Abort();
}
}

출력:

C# 스레드

2. 인터럽트()

Interrupt() 메소드가 호출될 때마다 WaitSleepJoin 스레드 상태에 있는 스레드가 중단됩니다.

3. 가입()

Join() 메서드가 호출될 때마다 호출 스레드는 스레드가 종료될 때까지 차단되며 스레드 차단과 함께 표준 COM 및 SendMessage 펌핑이 계속 수행됩니다.

Interrupt() 및 Join() 구현 예:

코드:

using System;
using System.Threading;
class Thr
{
Thread th;
public Thr(String name1)
{
th = new Thread(this.Runaway);
th.Name = name1;
th.Start();
}
public void Runaway()
{
Thread th1 = Thread.CurrentThread;
try
{
Console.WriteLine(" Execution of " + th1.Name + " has begun");
for(int y=0; y<3; y++)
{
Console.WriteLine(" Printing of " + th1.Name + " has begun" + y);
Thread.Sleep(200);
}
Console.WriteLine(" Execution of " + th1.Name + " is finished");
}
catch(ThreadInterruptedException e)
{
Console.WriteLine("Thread Interruption" + e);
}
}
public static void Main(String[] ar)
{
Thr ob = new Thr("Thread demo");
ob.th.Interrupt();
ob.th.Join();
}
}

출력:

C# 스레드

4. ResetAbort()

ResetAbort() 메소드가 호출될 때마다 현재 스레드에 대한 종료 요청이 취소됩니다.

예:

코드:

using System;
using System.Threading;
using System.Security.Permissions;
class Thread1
{
public void Jobthread()
{
try
{
for (int r = 0; r < 3; r++)
{
Console.WriteLine(" Working of thread has begun ");
Thread.Sleep(10);
}
}
catch (ThreadAbortException e)
{
Console.WriteLine("ThreadAbortException is caught and must be reset");
Console.WriteLine("The message looks like this: {0}", e.Message);
Thread.ResetAbort();
}
Console.WriteLine("Thread is working fine");
Thread.Sleep(200);
Console.WriteLine("Thread is done");
}
}
class Driver
{
public static void Main()
{
Thread1 obj = new Thread1();
Thread Th = new Thread(obj.Jobthread);
Th.Start();
Thread.Sleep(100);
Console.WriteLine("thread abort");
Th.Abort();
Th.Join();
Console.WriteLine("end of main thread");
}
}

출력:

C# 스레드

5. 시작()

Start() 메소드가 호출될 때마다 스레드가 시작됩니다.

예:

코드:

using System;
using System.Threading;
class Test
{
static void Main()
{
Thread td = new Thread (new ThreadStart (Got));
td.Start();
}
static void Got()
{
Console.WriteLine ("this is thread Start() method");
}
}

출력:

C# 스레드

6. 절전(int 밀리초Timeout)

Sleep(int millisecondsTimeout) 메서드가 호출될 때마다 지정된 시간 동안 스레드가 일시 중지됩니다.

예:

코드:

using System;
using System.Threading;
namespace Examplethr
{
class MyThread
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "This is the First Thread";
Console.WriteLine("The Name of the thread is : {0}", th.Name);
Console.WriteLine("The priority of the thread is : {0}", th.Priority);
Console.WriteLine("Pausing the child thread");
// using Sleep() method
Thread.Sleep(100);
Console.WriteLine("Resuming the child thread");
Console.ReadKey();
}
}
}

출력:

C# 스레드

7. Suspend()

Whenever Suspend() method is called, the current thread is suspended if it is not suspended.

8. Resume()

Whenever Resume() method is called, the suspended thread is resumed.

9. Yield()

Whenever Yield() method is called, the calling thread must result in execution to the other thread which is ready to start running on the current processor. The thread to yield to is selected by the operating system.

Example to implement Suspend() Resume() and Yield()

Code:

using System;
using System.Runtime.CompilerServices;
using System.Threading;
class Program
{
public static void Main ()
{
bool finish = false;
Thread th = new Thread (() => {
while (!finish) {}
});
Thread th1 = new Thread (() => {
while (!finish) {
GC.Collect ();
Thread.Yield ();
}
});
th.Start ();
th1.Start ();
Thread.Sleep (10);
for (int j = 0; j < 5 * 4 * 2; ++j) {
th.Suspend ();
Thread.Yield ();
th.Resume ();
if ((j + 1) % (5) == 0)
Console.Write ("Hello ");
if ((j + 1) % (5 * 4) == 0)
Console.WriteLine ();
}
finish = true;
th.Join ();
th1.Join ();
}
}

Output:

C# 스레드

위 내용은 C# 스레드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C#의 역직렬화다음 기사:C#의 역직렬화