C#/C#정리

[C#] Thread 쓰레드

반나무 2021. 9. 28. 20:06

Thread

스레드는 명령어를 실행하기 위한 스케줄링 단위

프로세스 내부에서 생성할 수 있다.

OS에서 멀티 스레딩을 지원한다면 하나의 프로세스가 여러 개의 스레드 자원을 가질 수 있다.

프로세스가 생성될 때 기본적으로 한 개의 스레드를 함께 생성하며 이를 main thread, primary thread라고 부른다.

 


Thread 상태 알아보기

Thread thread = Thread.CurrentThread;
Console.WriteLine(thread.ThreadState); // 출력결과 Running

Thread 생성

Thread 생성은 Trigger 쪽에 두지 않고 초기화 쪽에 두는것이 일반적이다.

using System.Threading;

Thread Mythread
Mythread = new Thread(new ThreadStart(작업할 메소드));

Thread 시작

대신 초기화쪽에 쓰레드 생성을 두면 계속 새로 생기는것이 아니라 이미 사용중인 쓰레드를 다시 시작하려고 하기때문에 에러가 난다.

그렇기 때문에 if문 처리로 쓰레드가 사용중인지 판단해야한다.

if (!Mythread.IsAlive)
{
    // 다른곳에서도 객체생성 할 수 있게 필드로 선언해 둔다.
    Mythread= new Thread(new ThreadStart(사용할 메소드));
    Mythread.Start(); // 쓰레드 시작
    //Mythread.Join(); // 끝날때까지 대기
}

 

Background, Foreground thread

Foreground thread : 프로그램의 실행 종료에 영향을 미치는 스레드

Background thread : 프로그램의 실행 종료에 영향을 미치지 않는 스레드

Thread Mythread = new Thread(threadFunc);
// 부모 스레드가 종료되면 자식 스레드도 종료된다.
Mythread.IsBackground = true;
Mythread.Start();

Join : Thread 대기

쓰레드가 끝날 때 까지 대기한다.

Mythread.Join();

Error

보호된 메모리를 읽거나 쓰려고 했습니다. 대부분 이러한 경우는 다른 메모리가 손상되었음을 나타냅니다.

인터프리터 관련 : 서드파티쪽에서 난 잘 모르지만 인터프리터를 건들고있기때문에

→ 쓰레드 내에서 이미 사용중인 메소드나 다른부분을 건들려고 할 때 많이 나온다.


winform, WPF 에서의 서브스레드가 메인스레드에 작업위임

// Running on the worker thread
string newText = "abc";
form.Label.Invoke((MethodInvoker)delegate {
    // Running on the UI thread
    form.Label.Text = newText;
});
// Back on the worker thread
 

How do I update the GUI from another thread?

Which is the simplest way to update a Label from another Thread? I have a Form running on thread1, and from that I'm starting another thread (thread2). While thread2 is processing some files I wo...

stackoverflow.com

 

반응형