gpt4 book ai didi

c# - 父类中的静态事件处理程序不会从嵌套类中的 Process.Exited 触发

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:49 25 4
gpt4 key购买 nike

每次调用 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);
}
}
}

最佳答案

首先,正如@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 时可能参差不齐。我不知道这是否也适用于 Exited 事件,但我会注意它并明确设置 UseShellExecute = false; 就像我在上面所做的那样。

关于c# - 父类中的静态事件处理程序不会从嵌套类中的 Process.Exited 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9116683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com