每次调用CurlFile()时,它都会从ProcessObject类创建一个新对象。 ProcessObject对象启动新进程。我希望每个对象中的Process.Exit事件触发父类中的静态事件处理程序,但它似乎没有因某种原因而起作用。
class Curl
{
StringContainer oStrings = new StringContainer();
private static int _counter = 0;
private string _curl;
public Curl()
{
//oStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
_curl = oStrings.Curl;
}
public void CurlFile(string _arg)
{
ProcessObject oProcessObject = new ProcessObject(_arg, _curl);
}
private static void oProcess_Exited(object sender, EventArgs e)
{
_counter++;
if (_counter == 1000)
{
MessageBox.Show("here");
}
}
private class ProcessObject
{
ProcessStartInfo oStartInfo = new ProcessStartInfo();
Process oProcess = new Process();
public ProcessObject(string _arg, string _curl)
{
oStartInfo.FileName = _curl;
oStartInfo.Arguments = _arg;
oProcess.EnableRaisingEvents = true;
oProcess.Exited += new EventHandler(oProcess_Exited);
oProcess = Process.Start(oStartInfo);
}
}
}
答案 0 :(得分:1)
首先,正如@Will所提到的,你需要保留对Process对象的引用,这样它们就不会得到GC。这样的事情(代码未经测试):
class Curl
{
internal static List<ProcessObject> _processes = new List<ProcessObject>();
// ....
private static void oProcess_Exited(object sender, EventArgs e)
{
var p = sender as Process;
if (p != null && _processes.Contains(p))
_processes.Remove(p);
_counter++;
if (_counter == 1000)
{
MessageBox.Show("here");
}
}
public ProcessObject(string _arg, string _curl)
{
oStartInfo.FileName = _curl;
oStartInfo.Arguments = _arg;
oStartInfo.UseShellExecute = false;
oProcess.EnableRaisingEvents = true;
oProcess.Exited += new EventHandler(oProcess_Exited);
oProcess = Process.Start(oStartInfo);
Curl._processes.Add(oProcess);
}
}
另外,作为some people have found,Process类可以检测到Exit。我不知道退出事件是否也适用,但我会注意并明确设置UseShellExecute = false;
,如上所述。