我想知道是否有一种监听事件的方法,以便在特定进程没有响应时(而不是退出时)得到通知。
这里的解决方案允许检查某个进程是否响应,但是该解决方案只能与轮询一起使用:Check status of process。如果我可以在此解决方案中“听” 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();
}
}
关于c# - 在进程停止响应(最好是C#)时获得通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26610834/