【发布时间】:2015-09-30 20:10:23
【问题描述】:
我们有这个第 3 方内部应用程序,它有一点问题,目前,在我们的 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 指令或程序集参考?)
怎么了?
【问题讨论】:
-
好吧,有您定义了您订阅事件
EventArrived、this.OnEventArrived的事件处理程序/回调方法?它有什么签名? -
哇,我不知道。显然没有,但我不知道该怎么做才能做到这一点。我假设我需要编写一个名为“OnEventArrived”的方法,它在事件到达时运行?我什至不确定它需要什么参数。那篇 CodeProject 文章甚至没有提及这一点。
-
您现在在下面得到了一个很好的答案,但我建议您花点时间研究 C# 委托和事件。这种事情会经常出现。