본문 바로가기
[2]SW Development Note/[2-2.2].NET CLR

[Thread Book #7 ] 포그라운드 스레드와 백그라운드 스레드

by 오늘도 빛나는 너에게 2020. 7. 26.
728x90
[Thread Book #7 ] 포그라운드 스레드와 백그라운드 스레드


class Program
       {
              static void Main(string[] args)
              {
                // 다른 두 스레드를 정의한 메인 프로그램을 시작한다.
                     var sampleForeground = new ThreadSample(10);
                     var sampleBackground = new ThreadSample(20);
                     var threadOne = new Thread(sampleForeground.CountNumbers);
                     threadOne.Name = "ForegroundThread";
                     var threadTwo = new Thread(sampleBackground.CountNumbers);
                     threadTwo.Name = "BackgroundThread";
                     threadTwo.IsBackground = true;
                     threadOne.Start();
                     threadTwo.Start();
              }
              class ThreadSample
              {
                     private readonly int _iterations;
                     public ThreadSample(int iterations)
                     {
                           _iterations = iterations;
                     }
                     public void CountNumbers()
                     {
                           for (int i = 0; i < _iterations; i++)
                           {
                                  Thread.Sleep(TimeSpan.FromSeconds(0.5));
                                  Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
                           }
                     }
              }
       }



결과 




설명 : 기본적으로 명시적으로 생성한 스레드는 포그라운드 스레드다.
        백그라운드 스레드를 생성하려면 "threadTwo" 객체의 "IsBackground" 속성을 True로 직접 설정한다.
       첫번째 스레드를 더 빠르게 끝내는 방식으로 스레드를 구성한후 프로그램을 실행한다.
       첫번째 스레드가 끝난 후에 프로그램은 멈추고 백그라운드 스레드를 종료한다.
       두 스레드간의 주요차이점이 있는데,프로세는 작업을 완료하기 전에 
       모든 포그라운드 스레드가 끝나길 기다리는 반면에 백그라운드 스레드가 있을 경우 종료할 뿐이다.
       프로그램이 끝나지 않은 포그라운드 스레드를 정의하면 
       메인 프로그램이 제대로 종료하지 못함을 언급하는 것도 중요하다.


출처 : C# 멀티스레드 프로그래밍 -유진 아가포노프 -  



728x90

댓글