Process.Start () zawiesza się podczas uruchamiania na wątku w tle
Cały dzień rozwiązuję problemy. Po zrobieniu kilkuBadania i wiele prób i błędów, wydaje mi się, że udało mi się zawęzić problem do faktu, że moje wezwanie doprocess.Start()
nie działa na wątku timera. Poniższy kod działa podczas uruchamiania w głównym wątku. Umieść ten sam kod w wywołaniu zwrotnym zegara i zawiesza się. Czemu? Jak sprawić, by działał z zegarem?
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();
}
EDYTOWAĆ
Jako test użyłem tego samego kodu na innym laptopie i doświadczyłem tego samego problemu. Jest to kompletny kod, który można wkleić do aplikacji konsoli.process.Start()
zawiesza się, ale jak tylko uderzę dowolny klawisz,process.Start()
kończy się przed zakończeniem programu.
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();
}