我想知道是否有一种方法可以监听事件,以便在特定进程没有响应时(而不是退出时)得到通知。
此解决方案允许检查某个进程是否响应,但此解决方案只能用于轮询:检查进程的状态。如果我能在这个解决方案中"听"process.Responding
,那就太好了。
例如,我希望在windows机器上监听所有Visual Studio进程,如果其中任何进程没有响应,我希望得到通知,以便我可以相应地采取行动。非常感谢!
这样的东西可以工作。这是一个使用Tasks轮询Process.Responding
并在返回false时激发事件的原始示例。我认为你无法定期对流程进行轮询,至少不能以简单/简洁的方式进行。
每个Task
将在后台线程中运行,以便在监视每个进程时不挂起主线程。
using System.Threading.Tasks;
namespace System.Diagnostics
{
public class ProcessEventArgs : EventArgs
{
public Process Process { get; protected set; }
public ProcessEventArgs( Process process )
{
this.Process = process;
}
}
public delegate void ProcessNotRespondingEvent( object sender, ProcessEventArgs e );
public class ProcessMonitor
{
public event ProcessNotRespondingEvent NotResponding;
protected Process mProcess;
public ProcessMonitor( Process process )
{
this.mProcess = process;
}
public async void Start()
{
Task t = null;
t = Task.Run( () =>
{
while( this.mProcess.Responding )
t.Wait( 1000 ); //1 second
this.OnNotResponding();
} );
await t;
}
protected void OnNotResponding()
{
if( this.NotResponding == null )
return;
ProcessEventArgs e = new ProcessEventArgs( this.mProcess );
this.NotResponding( this, e );
}
}
}
示例用法:
using System.Linq;
internal static class Program
{
private static void Main()
{
var processes = Process.GetProcessesByName( "devenv" );
var monitors = processes.Select( p => {
var monitor = new ProcessMonitor( p );
monitor.NotResponding += ( s, e ) => {
Console.WriteLine( "Process {0}(pid: {1}) has stopped responding.", e.Process.ProcessName, e.Process.Id );
};
return monitor;
} );
foreach( var monitor in monitors )
monitor.Start();
}
}