[C# 문법] C# 프로세스 시작하기, 끝내기, 기다리기

소개

  • 안녕하세요. 오늘은 C# 문법에서 프로세스 다루는 방법에 대해서 알려 드리려고 합니다.
  • 가장 기초가 되는 프로세스 시작하기, 끝내기, 기다리는 방법에 대해서 C# 으로 어떻게 표현하는지 보알려 드리겠습니다.
  • System.Diagnostics 네임스페이스에 정의돼 있는 Process 클래스를 이용하면 위의 내용들을 구현할 수 있습니다.
  • 예제 코드를 통해서 보여 드리겠습니다.

예제 코드

  • 아래 예제 코드를 보시게 되면, RunNotePadExe(), RunWaitNotePadExe() 2개의 메서드가 있습니다.
  • RunNotePadExe() 메서드는 메모장 경로를 입력하여, 메모장 프로세스를 시작하는 메서드 입니다.
  • RunWaitNotePadExe() 메서드는 메모장 프로세스가 실행되고, 특정 시간(밀리 초 단위) 이후에도 프로세스가 종료되지 않는다면 에러코드를 반환하고 에러를 출력하는 메서드 입니다.
  • 즉, 메모장이 실행된 후 10초 안에 메모장이 종료되지 않으면 TimeoutException 에러가 출력됩니다.
using System;
using System.Diagnostics;

namespace interfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // 메모장 실행하기
            RunNotePadExe();

            // 프로세스 끝나기를 기다리기
            RunWaitNotePadExe();
        }

        // 메모장(NotePad) 실행하기
        private static void RunNotePadExe()
        {
            // 메모장 실행 경로 입력
            var path = @"%systemRoot%\system32\notepad.exe";
            var fullPath = Environment.ExpandEnvironmentVariables(path);

            // 프로세스 시작하기
            Process.Start(fullPath);
        }

        /// <summary>
        /// 메모장 끝나기리를 기다리는 메서드
        /// </summary>
        /// <returns></returns>
        private static int RunWaitNotePadExe()
        {
            // 메모장 실행 경로 입력
            var path = @"%systemRoot%\system32\notepad.exe";
            var fullPath = Environment.ExpandEnvironmentVariables(path);

            using(var process = Process.Start(fullPath))
            {
                if(process.WaitForExit(10000)) // 밀리초 단위
                {
                    return process.ExitCode;
                }

                throw new TimeoutException();
            }
        }
    }
}

실행 결과

  • 메모장이 실행 되고, 10초가 지난뒤 아래와 같이 Timeout 에러가 출력된 것을 확인할 수 있습니다.

Unhandled exception. System.TimeoutException: The operation has timed out.
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY