我整天都在排除故障。在做了一些研究和大量试验和错误之后,似乎我已经能够将问题缩小到我的调用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();
}