为什么我总是得到InvalidOperationException?

时间:2014-03-05 23:01:48

标签: c# winforms

我知道这意味着什么,但我不明白为什么我会得到它。 在我的类构造函数中,我做了:

namespace HM
{
    class Core
    {
        public static Form1 form1;
        Process[] pname;
        private static List<float?> cpuSensorValues = new List<float?>();
        private static List<float?> gpuSensorValues = new List<float?>();
        Computer myComputer;
        Computer computer;

        public Core(Form1 f)
        {
            form1 = f;
            myComputer = new Computer();
            myComputer.CPUEnabled = true;
            myComputer.FanControllerEnabled = true;
            myComputer.MainboardEnabled = true;
            myComputer.Open();
            computer = new Computer();
            computer.Open();
            computer.GPUEnabled = true;
            OpenHardwareMonitor.Hardware.ISensor isss;
            Hardwares hwsd;
            OpenHardwareMonitor.Hardware.ISensor ist;
            pname = Process.GetProcessesByName("BFBC2Game");

        }

我补充说:

pname = Process.GetProcessesByName("BFBC2Game");

当游戏运行时,我看到使用断点,pname赢得了一个游戏进程的索引。我肯定先运行游戏然后运行程序。

然后我在类中有一个方法我用Form1中的一个计时器调用它,它将日志文件写入GPU视频卡的temeperature。 这部分工作得很好,直到我添加了这个pname进程。

if (gpuSensorValues.Count == 30 && sensor.Value >= (float)numericupdown)
                                        {
                                            float a = ComputeStats(gpuSensorValues).Item1;
                                            float b = ComputeStats(gpuSensorValues).Item2;
                                            float c = ComputeStats(gpuSensorValues).Item3;
                                            Logger.Write("********************************");
                                            Logger.Write("GPU Minimum Temperature Is ===> " + a);
                                            Logger.Write("GPU Maximum Temperature Is ===> " + b);
                                            Logger.Write("GPU Average Temperature Is ===> " + c);
                                            Logger.Write("********************************" + Environment.NewLine);
                                            gpuSensorValues = new List<float?>();
                                            pname.ToList().ForEach(p => p.Kill());

                                        }

我补充说:

pname.ToList().ForEach(p => p.Kill());

我希望如果温度为123c,那么立刻杀死/关闭/关闭游戏!相反,它不再向记录器文件写入温度,它永远不会杀死进程,而是将异常消息写入日志文件:

3/5/2014--4:10 AM ==> There was an exception: System.InvalidOperationException: No process is associated with this object.
   at System.Diagnostics.Process.EnsureState(State state)
   at System.Diagnostics.Process.EnsureState(State state)
   at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
   at System.Diagnostics.Process.Kill()
   at HardwareMonitoring.Core.gpuView(Boolean pause, List`1 myData, Nullable`1 myGpuTemp, Button b1, Decimal numericupdown) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Core.cs:line 172

如果需要,这是完整的方法代码:

public float? gpuView(bool pause, List<string> myData, float? myGpuTemp, Button b1, decimal numericupdown)
        {
            try
            {
                if (pause == true)
                {
                }
                else
                {


                    foreach (var hardwareItem in computer.Hardware)
                    {
                        if (form1.videoCardType("ati", "nvidia") == true)
                        {
                            HardwareType htype = HardwareType.GpuNvidia;

                            if (hardwareItem.HardwareType == htype)
                            {

                                foreach (var sensor in hardwareItem.Sensors)
                                {

                                    if (sensor.SensorType == SensorType.Temperature)
                                    {

                                        sensor.Hardware.Update();
                                        if (sensor.Value.ToString().Length > 0)
                                        {

                                            /* else if (UpdatingLabel(sensor.Value.ToString(), label16.Text.Substring(0, label16.Text.Length - 1)))
                                             {
                                                 //  Label8 = GpuText;
                                             }*/
                                            //myData = new List<string>();
                                            //this.Invoke(new Action(() => data = new List<string>()));
                                            if (!form1.IsDisposed)
                                            {
                                                form1.Invoke(new Action(() => myData.Add("Gpu Temeprature --- " + sensor.Value.ToString())));
                                            }
                                            //this.Invoke(new Action(() => listBox1.DataSource = null));
                                            //this.Invoke(new Action(() => listBox1.DataSource = data));



                                            //form1.Invoke(new Action(() =>  lb1.DataSource = myData));
                                            //sensor.Value.ToString() + "c";
                                            myGpuTemp = sensor.Value;
                                            //label8.Visible = true;
                                        }
                                        //if (sensor.Value > 60)
                                        //{
                                        gpuSensorValues.Add(sensor.Value);
                                        if (gpuSensorValues.Count == 30 && sensor.Value >= (float)numericupdown)
                                        {
                                            float a = ComputeStats(gpuSensorValues).Item1;
                                            float b = ComputeStats(gpuSensorValues).Item2;
                                            float c = ComputeStats(gpuSensorValues).Item3;
                                            Logger.Write("********************************");
                                            Logger.Write("GPU Minimum Temperature Is ===> " + a);
                                            Logger.Write("GPU Maximum Temperature Is ===> " + b);
                                            Logger.Write("GPU Average Temperature Is ===> " + c);
                                            Logger.Write("********************************" + Environment.NewLine);
                                            gpuSensorValues = new List<float?>();
                                            pname.ToList().ForEach(p => p.Kill());

                                        }
                                            b1.Enabled = true;
                                        //}
                                        //form1.Select();
                                    }
                                }
                            }
                        }
                        else
                        {
                            HardwareType htype = HardwareType.GpuAti;

                            if (hardwareItem.HardwareType == htype)
                            {

                                foreach (var sensor in hardwareItem.Sensors)
                                {

                                    if (sensor.SensorType == SensorType.Temperature)
                                    {

                                        sensor.Hardware.Update();
                                        if (sensor.Value.ToString().Length > 0)
                                        {

                                            myGpuTemp = sensor.Value;
                                            //label8.Visible = true;
                                        }
                                        if (sensor.Value > 60)
                                        {
                                            Logger.Write("The Current Ati GPU Temperature Is ===> " + sensor.Value); 
                                            b1.Enabled = true;
                                        }
                                        form1.Select();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Logger.Write("There was an exception: " + err.ToString());
            }
            return myGpuTemp;
        }

第172行是:

//form1.Select();

只是空行无处可做。

3 个答案:

答案 0 :(得分:1)

Process.Kill()的文档显示,如果进程未运行,它可能引发InvalidOperationException。

也许尝试:pname.Where(p => !p.HasExited).ToList().ForEach(p => p.Kill());

答案 1 :(得分:1)

问题是pname列表中的一个或多个实例未处于您期望的状态。正如另一个答案所指出的,这可能是因为该过程没有运行。此外,其中一个参考可能是null。要防止异常,请尝试添加如下的where子句;

 pname.ToList().Where(p != null && !p.HasExited).ForEach(p => p.Kill());

我不熟悉Process类,所以我不完全确定你想要在Where中使用第二个条件,但这应该会给你一个想法。这只会在调用Kill()之前过滤掉列表中可能导致错误的实例。

答案 2 :(得分:0)

我能在代码中看到的唯一问题是你没有清除pname对象。如果pname引用了不再运行的进程,则会出现此异常。我建议您在想要停止时获取新的流程列表。替换以下行

pname.ToList().ForEach(p => p.Kill());

pname = Process.GetProcessesByName("BFBC2Game");
pname.ToList().ForEach(p => p.Kill());