블로그 이미지
따시쿵

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2015. 5. 15. 11:58 C# with Service Program

프로그램 설명


윈도우즈 서비스 프로그램을 디버깅하는 예제입니다.

디버깅하는 방법은 콘솔 프로그램 같이 F10 버튼을 이용하여 다음 단계로 넘어가는 것입니다.


1. visual syudio 2013 을 관리자 권한으로 실행


2. 프로그램 출력 형식을 [콘솔 응용 프로그램]으로 변경



3. 현재 프로그램이 대화형으로 실행되고 있는지 확인하는 로직 추가


기존의 Main  method를 다음과 같이 변경함. Environment.UserInteractive 를 이용해서 확인합니다. 그리고 테스트 TestStartupAndStop method를 추가합니다.


        static void Main(string[] args)
        {
            if (Environment.UserInteractive)
            {
                MyNewService2 service2 = new MyNewService2();
                service2.TestStartupAndStop(args);
            }
            else
            {
                // Put the body of your old Main method here.
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new MyNewService2() 
                };
                ServiceBase.Run(ServicesToRun);
            }
        }

TestStartupAndStop method를 기술합니다.

        #region TestStartupAndStop
        internal void TestStartupAndStop(string[] args)
        {
           Console.WriteLine("TestStartupAndStop");
           this.OnStart(args);
           LogFile.WriteLog("TestStartupAndStop");
            
            Console.ReadLine();
            this.OnStop();
        }
        #endregion


4. 단일 thread 인 경우, 사용자 thread 가 있는 경우


메인 Thread 에서 작업하는 경우, 즉 단일 쓰레드에서 사용자 작업을 하는 경우에는 OnStart() 안에 로직을 추가하면 됩니다.


그러나, 메인 Thread 외에 사용자 Thread를 이용하는 경우에는, 메인 Thread가 사용자 쓰레드가 정지 할때까지 기달려야 합니다. 그래서 기존의 OnStart() 안에 thread_handler.Join(); 코드를 추가했습니다.

        #region OnStart
        protected override void OnStart(string[] args)
        {
            LogFile.WriteLog("OnStart");
                        
            // Create the sub working thread...
            Thread thread_handler = new Thread(socketMain.StartSocket);
            thread_handler.IsBackground = true;
            thread_handler.Start();

            if (Environment.UserInteractive)
            {
                   thread_handler.Join();
            }
        }
        #endregion



실행 화면



소스 파일 : 

MyNewService2_debug.zip






'C# with Service Program' 카테고리의 다른 글

[C#] 서비스 프로그램 - 2  (0) 2015.05.14
[C#] 서비스 프로그램 - 1  (0) 2015.05.11
posted by 따시쿵