好像進程退出處理可能造成應用程序錯誤。所以應用程序可能已經終止。你可以把一個適當的try..catch塊和調試,看看有什麼問題。或註釋 線
newCrawler.Exited += new EventHandler(newCrawler_Exited);
and see what happens.
請嘗試以下代碼(這是從MSDN),也不要忘了傳遞一個參數(文件名)
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;
class PrintProcessClass
{
private Process myProcess = new Process();
private int elapsedTime;
private bool eventHandled;
// Print a file with any known extension.
public void PrintDoc(string fileName)
{
elapsedTime = 0;
eventHandled = false;
try
{
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = fileName;
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
return;
}
// Wait for Exited event, but not more than 30 seconds.
const int SLEEP_AMOUNT = 100;
while (!eventHandled)
{
elapsedTime += SLEEP_AMOUNT;
if (elapsedTime > 30000)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
}
}
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
eventHandled = true;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
}
public static void Main(string[] args)
{
// Verify that an argument has been entered.
if (args.Length <= 0)
{
Console.WriteLine("Enter a file name.");
return;
}
// Create the process and print the document.
PrintProcessClass myPrintProcess = new PrintProcessClass();
myPrintProcess.PrintDoc(args[0]);
}
}
有一件事我就是注意到了,如果你沒有傳遞文件名作爲參數,這會導致進程崩潰,但應用程序仍然是完整的(因爲異常在進程內部處理)。
如果您沒有傳遞文件名,上面的代碼會崩潰,因爲myPrintProcess.PrintDoc(args [0])是 ; 會從主進程本身拋出異常。 我試圖在Exit處理程序中創建一個exceptin,那時應用程序(主進程)也崩潰了。
你可以嘗試評論退出處理程序內的代碼嗎?
謝謝,但我需要使用退出事件,因爲我不想阻止該應用程序,直到進程存在 – Ehsan 2011-01-14 09:45:39
好,但誰是保持主處理(控制檯應用程序)仍在運行?你說它退出... – 2011-01-14 09:47:01