3

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

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

4

1 回答 1

2

这是进行实际监控的方法。FileSystemWatcher就动态配置文件而言,产生这些监控线程的主线程可以使用http://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);
于 2012-11-14T04:29:56.307 回答