c# - 启动流程然后引发事件以监视它们

标签 c# process timer

我正在启动一个运行外部第 3 方包的进程。然后我想启动一个定时器,每隔几秒触发一个事件来监视这个过程的输出。这是我用来启动该过程的代码:

Process process = new Process();
process.StartInfo.FileName = exe;
process.StartInfo.Arguments = args;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.BeginErrorReadLine();
RuntimeMonitor rtm = new RuntimeMonitor(OutputFile(), InputFile(), 5000);
process.WaitForExit();
rtm.Close();

运行时监视器的构造函数是:

public RuntimeMonitor(string _outfile,
                      string _title,
                      double intervalMs) // in milliseconds
{
    outFile = outfile;
    title = _title;
    timer = new System.Timers.Timer();
    timer.Interval = intervalMs;
    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_func);
    timer.AutoReset = true;
    timer.SynchronizingObject = null;
    timer.Start();
}

我得到的症状是直到进程结束(即在 process.WaitForExit(); 完成之后)才会调用 timer_func。我以为 timer elapsed 事件是异步触发的,但它似乎被锁定了

编辑:好吧,它变得陌生了。我确实尝试将 timer.SynchronizingObject 设置为 null,但无济于事。我也尝试使用 System.Threading.Timer 类并得到相同的结果。

还有一条信息。我确实发出了开始从流程中收集数据的调用,但不确定是否相关(即上面代码中的 BeginErrorReadLine 调用)

最佳答案

我不确定为什么您的计时器似乎没有启动。我拿了你的代码并对其进行了一些结构化以尝试测试它。下面的代码工作得很好。也许您可以使用它来让您的工作正常进行。

void Main()
{
    Process process = new Process();
    process.StartInfo.FileName = "notepad.exe";
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();
    RuntimeMonitor rtm = new RuntimeMonitor(5000);
    process.WaitForExit();
    rtm.Close();
}

public class RuntimeMonitor
{
    System.Timers.Timer timer;

    // Define other methods and classes here
    public RuntimeMonitor(double intervalMs) // in milliseconds
    {
        timer = new System.Timers.Timer();
        timer.Interval = intervalMs;
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_func);
        timer.AutoReset = true;
        timer.Start();
    }

    void timer_func(object source, object e)
    {
        Console.WriteLine("Yes");
    }

    public void Close()
    {
        timer.Stop();
    }
}

关于c# - 启动流程然后引发事件以监视它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9038931/

相关文章:

c# - 使用 DbContext Set<T>() 而不是在上下文中公开

c# - 是否可以将 SQLite.NET 与不可变记录类型一起使用?

linux - 如何找到最后一个spwan线程或进程?

c++ - 如何使用 POSIX 在 C++ 中执行命令并获取命令的输出?

c - 定时器回调中的长过程

java - 如何停止带有定时器的软件一遍又一遍地重复?

在较旧的 .net 版本上运行的 C#

c# - 为什么 C#.net 中的表达式主体不能使用 int、double 或 bool 类型的属性?

bash - 如何杀死一个nohup进程?

java - 关于Swing定时器的一些问题