【问题标题】:Monitor multiple variable amounts of processes' start and exit [closed]监控多个可变数量的进程的启动和退出[关闭]
【发布时间】:2012-11-14 04:22:30
【问题描述】:

我需要一些代码来异步监控程序何时启动和停止。

我可以使用 VB.NET 或 C# 代码。谢谢。

【问题讨论】:

标签: c# vb.net process monitor


【解决方案1】:

这是进行实际监控的方法。至于动态配置文件,产生这些监控线程的主线程可以使用FileSystemWatcherhttp://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx 来监控带有进程名称的xml/文本文件。您可以将取消令牌传递给函数,并在每次迭代时检查令牌是否被取消。

static Task MonitorProcessAsync(string process, Action<string> startAction, Action<string> exitAction)
{
    return Task.Factory.StartNew(() =>
    {
        bool isProcessRunning = false;

        while (true)
        {
            int count = Process.GetProcessesByName(process).Count();
            if (count > 0 && !isProcessRunning)
            {
                startAction(process);
                isProcessRunning = true;
            }
            else if (count == 0 && isProcessRunng)
            {
                exitAction(process);
                isProcessRunning = false;
            }

            Thread.Sleep(1000);
        }
    });
}

例子

Action<string> startAction = (process) => Console.WriteLine(process + " Started!");
Action<string> exitAction = (process) => Console.WriteLine(process + " Stopped!");
MonitorProcessAsync("notepad.exe", startAction, exitAction);

【讨论】:

  • 抱歉,我不得不重新提出我的问题,我必须同时监控进程的启动和退出。
  • 没关系。我对其进行了修改以监视进程的开始和停止。它使用布尔值来表示进程的先前状态,并根据当前计数检查它的状态是否有机会,如果有,它会执行适当的启动或存在操作。
猜你喜欢
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
相关资源
最近更新 更多