进程的C#.NET监视

时间:2015-09-30 20:10:23

标签: c# .net wmi

我们有第三方内部应用程序,这是一个小小的错误,现在,直到它已修复,在我们的Citrix环境中,我需要密切关注它并杀死过程,如果它运行太长时间。我能够对它进行轮询并在它运行时将其杀死,但这很脏,并且需要我使用计划任务。我想要一个服务来监控和检测它,然后如果它运行的时间太长就杀掉它。

所以我在Visual Studio中启动了一个Windows服务项目,发现this code from CodeProject使用ManagementEventWatcher向WMI注册:

        string pol = "2";
        string appName = "MyApplicationName";

        string queryString =
            "SELECT *" +
            "  FROM __InstanceOperationEvent " +
            "WITHIN  " + pol +
            " WHERE TargetInstance ISA 'Win32_Process' " +
            "   AND TargetInstance.Name = '" + appName + "'";

        // You could replace the dot by a machine name to watch to that machine
        string scope = @"\\.\root\CIMV2";

        // create the watcher and start to listen
        ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
        watcher.EventArrived += new EventArrivedEventHandler(this.OnEventArrived);
        watcher.Start();

此代码的问题在于它显示“this.OnEventArrived”,我收到以下错误:

错误1'MyServiceApp.Service1'不包含'OnEventArrived'的定义,并且没有扩展方法'OnEventArrived'可以找到接受类型'MyServiceApp.Service1'的第一个参数(你是否缺少using指令或程序集)引用?)

这是什么交易?

1 个答案:

答案 0 :(得分:2)

可以在MSDN上找到相关文档 https://msdn.microsoft.com/en-us/library/system.management.managementeventwatcher.eventarrived%28v=vs.110%29.aspx

OnEventArrived应该是这样的。

private void OnEventArrived(object sender, ManagementEventArgs args)
{
//do your work here
}

这是一个监控记事本的示例程序。您可能希望阅读有关WMI的更多信息,以了解是否有更好的方法。您可以通过开始菜单启动记事本,您将看到记事本开始输入控制台。退出时将打印记事本退出。我不知道可以输出的所有消息。

    static void Main(string[] args)
    {

        string pol = "2";
        string appName = "Notepad.exe";

        string queryString =
            "SELECT *" +
            "  FROM __InstanceOperationEvent " +
            "WITHIN  " + pol +
            " WHERE TargetInstance ISA 'Win32_Process' " +
            "   AND TargetInstance.Name = '" + appName + "'";

        // You could replace the dot by a machine name to watch to that machine
        string scope = @"\\.\root\CIMV2";

        // create the watcher and start to listen
        ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
        watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
        watcher.Start();
        Console.Read();
    }

    private static void OnEventArrived(object sender, EventArrivedEventArgs e)
    {
        if (e.NewEvent.ClassPath.ClassName.Contains("InstanceCreationEvent"))
            Console.WriteLine("Notepad started");
        else if (e.NewEvent.ClassPath.ClassName.Contains("InstanceDeletionEvent"))
            Console.WriteLine("Notepad Exited");
        else
            Console.WriteLine(e.NewEvent.ClassPath.ClassName);
    }