我已经排查了一整天。 做一些经过研究和大量的试验和错误的,看来我已经能够发出缩小的事实,我调用process.Start()
没有一个计时器线程工作。 主线程上运行时,下面的代码工作。 把该完全相同的代码在计时器回调,并且死了。 为什么? 我如何得到它具有定时工作?
private static void RunProcess()
{
var process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "/c exit";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start(); // code hangs here, when running on background thread
process.StandardOutput.ReadToEnd();
process.WaitForExit();
}
编辑
作为测试,我用另一台笔记本电脑这种完全相同的代码,我经历了同样的问题。 这是一个可以粘贴到一个控制台应用程序的完整代码。 process.Start()
挂,但只要我按任意键结束, process.Start()
程序结束前完成。
private static System.Timers.Timer _timer;
private static readonly object _locker = new object();
static void Main(string[] args)
{
ProcessTest();
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
private static void ProcessTest()
{
Initialize();
}
private static void Initialize()
{
int timerInterval = 2000;
_timer = new System.Timers.Timer(timerInterval);
_timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
_timer.Start();
}
private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
if (!Monitor.TryEnter(_locker)) { return; } // Don't let multiple threads in here at the same time.
try
{
RunProcess();
}
finally
{
Monitor.Exit(_locker);
}
}
private static void RunProcess()
{
var process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "/c exit";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start(); // ** HANGS HERE **
process.StandardOutput.ReadToEnd();
process.WaitForExit();
}