Visual C#을 사용하여 셸된 애플리케이션이 완료될 때까지 기다립니다.

이 문서에서는 Microsoft .NET Framework Process 클래스를 사용하여 코드에서 다른 애플리케이션을 시작하고 코드가 다른 애플리케이션이 계속되기 전에 닫을 때까지 대기하도록 하는 방법을 보여줍니다.

원래 제품 버전: Visual C# .NET
원래 KB 번호: 305369

요약

코드가 애플리케이션이 완료되기를 기다리는 경우 다음 두 가지 옵션이 있습니다.

  • 다른 애플리케이션이 완료되거나 사용자가 닫을 때까지 무기한 대기합니다.
  • 코드에서 애플리케이션을 닫을 수 있는 시간 제한 기간을 지정합니다.

이 문서에서는 두 가지 방법을 모두 보여 주는 두 가지 코드 샘플을 제공합니다. 또한 시간 제한 예제를 사용하면 다른 애플리케이션이 응답을 중지(중단)하고 애플리케이션을 닫는 데 필요한 단계를 수행할 수 있습니다.

이 문서에서는 다음 .NET Framework 클래스 라이브러리 네임스페이스 를 참조합니다System.Diagnostics.

네임스페이스 포함

다음 예제를 실행하기 전에 클래스의 Process 네임스페이스를 가져와야 합니다. 코드 샘플을 포함하는 네임스페이스 또는 클래스 선언 앞에 다음 코드 줄을 배치합니다.

using System.Diagnostics;

셸된 애플리케이션이 완료될 때까지 무기한 대기

다음 코드 샘플은 다른 애플리케이션(이 경우 메모장)을 시작하고 애플리케이션이 종료되기를 무기한 대기합니다.

//How to Wait for a Shelled Process to Finish
//Get the path to the system folder.
string sysFolder=
Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set the file name member of the process info structure.
pInfo.FileName = sysFolder + @"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for the window to finish loading.
p.WaitForInputIdle();
//Wait for the process to end.
p.WaitForExit();
MessageBox.Show("Code continuing...");

셸된 애플리케이션에 대한 시간 제한 제공

다음 코드 샘플에서는 셸된 애플리케이션에 대한 시간 초과를 설정합니다. 예제의 제한 시간은 5초로 설정됩니다. 테스트에 대해 이 수(밀리초 단위로 계산됨)를 조정할 수 있습니다.

//Set a time-out value.
int timeOut=5000;
//Get path to system folder.
string sysFolder=
    Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set file name to open.
pInfo.FileName = sysFolder + @"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for window to finish loading.
p.WaitForInputIdle();
//Wait for the process to exit or time out.
p.WaitForExit(timeOut);
//Check to see if the process is still running.
if (p.HasExited == false)
    //Process is still running.
    //Test to see if the process is hung up.
    if (p.Responding)
        //Process was responding; close the main window.
        p.CloseMainWindow();
    else
        //Process was not responding; force the process to close.
        p.Kill();
    MessageBox.Show("Code continuing...");

문제 해결

경우에 따라 이러한 두 옵션 중에서 선택하기 어려울 수 있습니다. 시간 제한의 주요 목적은 다른 애플리케이션이 중단되었기 때문에 애플리케이션이 중단되지 않도록 하는 것입니다. 시간 제한은 백그라운드 처리를 수행하는 셸된 애플리케이션에 더 적합하며, 사용자가 다른 애플리케이션이 중단되었거나 닫을 수 있는 편리한 방법이 없을 수 있습니다.