gpt4 book ai didi

进程的 C#.NET 监控

转载 作者:行者123 更新时间:2023-12-04 02:17:59 28 4
gpt4 key购买 nike

我们有这个 3rd party in house 应用程序,但现在,在我们的 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”的定义,并且找不到接受“MyServiceApp.Service1”类型的第一个参数的扩展方法“OnEventArrived”(您是否缺少 using 指令或程序集引用?)

这是怎么回事?

最佳答案

这方面的文档可以在 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 的内容,看看是否有更好的方法。您可以通过开始菜单启动记事本,您将看到记事本已启动到控制台。退出时会打印 Notepad Exited。不知道所有可以输出的消息。

    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);
}

关于进程的 C#.NET 监控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32874744/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com