我正在启动一个运行外部第 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/