2013-02-06 3 views
-1

실행중인 Windows 프로세스를 모니터링하는 코드를 작성했습니다. 특정 프로세스가 언제 시작되고 언제 종료되는지 알고 싶습니다. 코드는 원하는대로 작동합니다.프로세스를 지속적으로 모니터링합니다.

이제 Windows 용 서버 응용 프로그램에 구현하고 싶습니다. 양식이 살아있는 한 루프에서 실행됩니다. 나는 비동기 적으로 BackgroundWorker을 사용하여 실행해야한다고 생각합니다. 나는 그것을하기위한 최선의 방법과 방법이 무엇인지 모릅니다.

using System; 
using System.Management; 
using System.Diagnostics; 
using System.Collections.Generic; 
using System.ComponentModel; 

class ProcessMonitor 
{ 
    public static void Main() 
    { 
     Dictionary<string, Process> newProcs= new Dictionary<string, Process>(); 
     while (true) 
     { 
      foreach (Process process in Process.GetProcesses()) 
      { 
       if (process.ProcessName.CompareTo("Someprocess") == 0) 
       { 
        if (!searchForProcess(newProcs, process.Id)) 
        { 
         ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id); 
         foreach (ManagementObject @object in searcher.Get()) 
         { 
          Console.Write("Adding new Process: "); 
          Console.WriteLine(@object["CommandLine"] + " "); 
          newProcs.Add(@object["CommandLine"] + " ", process); 
         } 
        } 
       } 
      } 
      checkProcesses(newProcs); 
     } 
     Console.WriteLine("Done"); 
    } 

    private static bool searchForProcess(Dictionary<string, Process> newProcs, int newKey) 
    { 
     foreach (Process process in newProcs.Values) 
     { 
      if (process.Id == newKey) 
       return true; 
     } 

     return false; 
    } 
    private static void checkProcesses(Dictionary<string, Process> newProcs) 
    { 
     foreach (string currProc in newProcs.Keys) 
     { 
      bool processExists = false; 
      foreach (Process process in Process.GetProcesses()) 
      { 
       if (process.Id == newProcs[currProc].Id) 
       { 
        processExists = true; 
        break; 
       } 

      } 
      if (!processExists) 
      { 
       Console.Write("Process Finished: "); 
       Console.WriteLine(currProc); 
       newProcs.Remove(currProc); 
       if (newProcs.Count == 0) 
        break; 
      } 
     } 
    } 
} 

어떤 아이디어 : 여기

내 모니터 코드?

+0

는 "윈도우 폼 서버 응용 프로그램"으로 무엇을 의미합니까? –

+0

타이머를 사용할 수 있습니다. 어떻게 작동해야하는지에 대한 사양이 있습니까? – Jocke

+0

내 서버 쪽은 콘솔 응용 프로그램이 아닌 Windows 양식 응용 프로그램입니다. 기본적으로 클라이언트는 서버에 명령 요청을 보내고 서버는 명령 요청을 실행합니다. 그 명령을 추적하고 각 명령이 끝날 때 클라이언트에 알리고 싶습니다. – Idanis

답변

-1

유는이 새로운 방법의 주요 작성이

public static void Thread1() { 
      //paste your main code hear 
      } 

사본과 같은 모든 코드 과거의 방법을 만들 수 있습니다. 같은 일부

변화를 주이

public static void Main() { 
      Console.WriteLine("Before start thread"); 
      Thread tid1 = new Thread(new ThreadStart(Thread1)); 
      tid1.Start();     
    } 
+0

좋아, 나는 서버에서 그렇게했다. 문제는 이제'tid1.Start();를 사용하면 어떤 이유로 x를 닫을 때 양식이 종료되지 않습니다. 모든 아이디어가 있습니까? – Idanis

+0

양식 닫기 이벤트에서 'tid1.Stop();'을 호출해야합니다. –

1

이미 WMI를 사용하고 있으므로 temporary event subscription을 사용하여 프로세스 변경 사항을 확인하는 것이 좋습니다. 이 과정은 동기, 비동기, 또는 반 동기 (usually the recommended choice)이 될 수 있으며,이 쿼리 프로세스 생성 이벤트를 감시하는 WITHIN clause.

와 폴링 간격을 지정할 수 있습니다

SELECT TargetInstance FROM __InstanceCreationEvent 
    WHERE TargetInstance ISA "Win32_Process" -- or Win32_ProcessStartTrace 

이 하나의 프로세스 종료를 감시 이벤트 :

SELECT TargetInstance FROM __InstanceDeletionEvent 
    WHERE TargetInstance ISA "Win32_Process" -- or Win32_ProcessStopTrace 

This question가 C 번호에 ManagementEventWatcher 클래스를 사용하는 방법의 예를 가지고있다.

3

이것은 가입 또는 폴링을 사용하여 수행 할 수 있습니다. (프로세스 루프)

폴링 BackgroundWorker에

당신은 백그라운드에서 실행되며 UI와 상호 작용해야하는 하나의 작업이있는 경우

  • .

  • 스레드 풀 스레드

    효율이 요구되는 경우. 스레드를 생성하고, 시작하고, 스레드를 중지하는 것과 관련된 오버 헤드를 피할 수 있습니다. 장기간 실행되는 작업에는 적합하지 않습니다.

  • 장기 실행 작업에 대한

    Thread 클래스와 스레드 실행 등 세밀한 제어를 필요로 할 때. (언급 stuartd 무엇을) Subscripton

    • ManagementEventWatcher

    이 시나리오 가입에

아마 폴링보다 더 효율적이다.

관련 문제