問題描述
進程 WaitForExit 不等待 (Process WaitForExit not waiting)
我創建了 Print spooler 應用程序來異步打印 pdf。
(應用程序使用veryPDF 命令從網絡打印機打印)
這裡是代碼
var procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", " /c" + "E:\pdfprint_cmd\pdfprint.exe ‑$ 388444444448350FA394 E:\PrintSpoolerApplication\PrintSpoolerApplication\bin\Debug\45940.pdf");
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
procStartInfo.Verb = "runas";
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
var proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// Some stuff
但它沒有等待 WaitForExit 代碼。即使我的文檔在打印機隊列中,它也確實執行了(這裡//有些東西)。
還有其他方法可以在打印完成時通知嗎?
參考解法
方法 1:
Your code waits for cmd.exe
to finish, which (probably) terminates immediately after it has started pdfprint.exe
as a child process. I suggest you
- either start
pdfprint.exe
directly (why do you need the Windows command line here anyway?) - or find the Process object of the child process ‑‑ e.g. through WMI, as described here ‑‑ and wait for that process to exit instead.
However, both approaches only work if pdfprint.exe
actually waits for the scheduled print job to be completed. I don't know the tool, so I have no idea if it behaves that way. If it doesn't, you would have to access the print queue, which (as pointed out by Hans in his comment) is not recommended.
方法 2:
Here's a If‑Everything‑Else‑Fails approach you might have to take (if pdfprint.exe doesn't wait until completion for termination). It's ugly, but it'll work:
- Enter a while loop until the destination file exists (ideally with a timeout, in case pdfprint.exe runs into a problem and never generates the file)
- Enter a second while loop, where every X milliseconds (say, 500? 1000?), it checks the file length of the output PDF. If the file size is the same between checks, you assume the output process is finished and begin working with the file.
Like I said, it's not pretty (and you shouldn't use it unless you have no recourse)... but it gets the job done. I've had to use this sort of approach for handling incoming files being copied over the network (you need to process files when they come in, but you need to know that the file is finished being copied before touching it, because PDFs will lock as soon as they're opened and then the file‑copy will fail.)
方法 3:
Have you tried this?
procStartInfo.LoadUserProfile = true;
(by Munavvar、Robert Petermeier、Kevin、NotHere)