为什么我有两个相同进程的实例?

时间:2018-06-04 21:10:40

标签: c# .net asynchronous memory process

所以我正在玩我的一个项目,现在导致问题的是当我点击我的Start按钮这个方法运行时。

public void Start()
        {
            if (!ServerIsRunning)
            {
                ConsoleOutput.Clear();

                pServer = new Process();
                pServer.StartInfo.FileName = "java";
                pServer.StartInfo.Arguments = @"-jar " + "-Xms512M -Xmx1G myJavaFile.jar";

                pServer.Start();
                PID = pServer.Id;

                counter = new PerformanceCounter("Process", "% Processor Time", pServer.ProcessName, true);

                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += timer_Tick;
                timer.Start();
            }
        }

我为PerformanceCounter创建了一个全局null属性,如此

private PerformanceCounter counter;

正如你在start方法中看到的那样,我们为它赋予了一个值。

我创建了这个tick事件以及我更新属性的计时器

void timer_Tick(object sender, EventArgs e)
        {
            FindServerProcess();
            double pct = counter.NextValue() / 10;
            ServerCPU = pct.ToString("0.0");
        }

这里是找到与某个PID

对应的进程的方法
public void FindServerProcess()
{
    Process[] processes = Process.GetProcesses();
    foreach (var process in processes)
    {
        if (process.Id == PID)
        {
            Console.WriteLine("Found the process!");
        }
    }
}

当我点击“开始”时,让我知道在“输出”窗口中,它通过打印出消息Found the process!按预期找到了该过程。

然而..这就是它变得奇怪的地方。 如果我点击我的停止按钮

private void Stop(string StopCommand) 
{
     counter.Close();
     counter = null;
     timer.Stop();
     pServer.StandardInput.WriteLineAsync(StopCommand);
}

它关闭计数器,使其为null并且我停止调用tick事件的计时器。然后我还发出一个命令,它只是stop到控制台流,它只是关闭进程。 此时此过程已关闭,我无法再在任务管理器中看到它。 然而,当我点击“开始”时,它会在当时平行的情况下开始两次Found the process!,并且它正在改变的属性值似乎是双倍的。这是为什么?我没有安全关闭房产吗?或者我忘了丢弃一些物品了?

1 个答案:

答案 0 :(得分:2)

我认为您的Found the process!两行问题是由Start()函数引起的,特别是行:

timer.Tick += timer_Tick;

当您描述按下,开始,停止,然后再次开始时的操作。 timer.Tick事件被添加两次(每次运行Start()函数时都会添加一次。

要反击它,只需添加行

即可
timer.Tick -= timer_Tick;

预先。

每当您在运行时添加事件处理程序时,您应始终在调用之前使用-=语法删除先前分配的事件处理程序(除非您确实希望它运行多次)

相关问题