问题
I have this code here that starts a process wait 8 seconds and then kill it and again.
for (int i = 0; i < 20; i++)
{
Process pro = new Process();
pro.StartInfo.FileName = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
pro.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
pro.Start();
Thread.Sleep(8000);
try
{
pro.Kill();
Thread.Sleep(1000);
}
catch
{
return;
}
}
As i run the application either on debug mode or direct from the .exe , it successfully starts and kills the process but it is frozen. I cant move its window around or click on other buttons..
回答1:
it is frozen. I cant move its window around or click on other buttons.
That's correct. You said to put the thread to sleep.
People seem to have this strange idea that running code when buttons are pressed happens by magic. It does not happen by magic. It happens because the thread runs code that processes the "a button was clicked" message from the operating system. If you put a thread to sleep then it stops processing those messages, because it is asleep.
Putting a thread to sleep is 99% of the time the completely wrong thing to do, so just don't do it.
The right thing to do in C# 5 is to make your method async
and then do an await Task.Delay(whatever)
. Alternatively, create a timer that ticks after some number of seconds. In the tick handling event, turn the timer off and do your logic there.
回答2:
Well, my initial guess is that you are doing this all on your UI Thread. Since you make the UI thread sleep, your application will be frozen.
The obvious solution would be doing this in a new thread.
As Servy sais, this is not a great idea. You can use a Timer (https://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx) to do the waiting instead of blocking the UI thread.
回答3:
The main thread of your application is a loop that constantly peeks messages from Windows message queue. It's like cooperative multi-threading - if you don't update your UI explicitly it won't do that automatically. And it won't because your program (main thread) just spawns a process then sleeps and then kills it (you don't even need that try/catch block
- any exception on any thread of your application will terminate it). Sleeping within a thread blocks it. And because you sleep in the main thread (UI) you block the application from peeking from the message queue.
来源:https://stackoverflow.com/questions/29374831/c-sharp-program-freezes-in-for-loop