My problem is simple. I have an application, in which I create and call a sub thread. My sub thread launches a notepad, where a user inputs some values and then closes it. My application then takes the information from the notepad for additional processing. The problem is that my main thread doesn't wait for the sub thread to end (notepad to be closed), to perform the additional processing.
I could have used a form t开发者_如何学运维o gather these inputs, but I wish to have a program that is minimalistic. Today, the inputs are from a notepad. Tommorow, it may be from MS Office or OpenOffice. Can someone please provide some guidance? Regards.
I think there's a simpler approach here. The Process class has an Exited event that you can sign up for:
var process = new Process();
process.StartInfo = new ProcessStartInfo("notepad.exe");
process.EnableRaisingEvents = true;
process.Exited += (o, e) =>
{
Console.WriteLine("Closed");
};
process.Start();
The command you need is Thread.Join
In the code for the helper thread:
using ( Process p = Process.Start(...your parameters here...) ) {
// waits for the user to close the document
p.WaitForExit();
// TODO: postprocessing of the edited document
}
In your Main method:
static void Main(string[] args) {
...
Thread helperThread = // TODO: create thread
helperThread.Start();
// TODO: do other things
...
// Wait for the helper thread to exit
helperThread.Join();
}
You have to wait for the started process to exit (Process.WaitForExit
) and wait for the thread to exit as well (Thread.Join
).
That said, you don't have to use a separate thread, you can start the process in the main thread. Editing of the document runs in parallel anyway. Just use WaitForExit
when you need the output.
精彩评论