簡體   English   中英

我不時得到異常InvalidOperationException:如何修復它?

[英]From time to time im getting exception InvalidOperationException: how can fix it?

if (!f1.IsDisposed)
{
    Thread.Sleep(1000);
    f1.Invoke(new Action(() => myData.Add("Cpu Temeprature --- " + sensor.Value.ToString())));
}

例外是在線:

f1.Invoke(new Action(() => myData.Add("Cpu Temeprature --- " + sensor.Value.ToString())));

在課堂上我做了:

public static Form1 form1;

然后:

public Core(Form1 f)
        {
            form1 = f;

我這樣做的原因是在這個類中我獲得了CPU和GPU的溫度。 這是完整的類代碼,可以更輕松地查看我在做什么以及如何使用form1變量:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenHardwareMonitor.Hardware;
using System.Diagnostics;
using DannyGeneral;
using System.Windows.Forms;
using System.Threading;
using System.Management;

namespace HardwareMonitoring
{
    class Core
    {
        public static Form1 form1;

        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;


        }

        public float? cpuView(bool pause , CpuTemperature cpuTemp , Form1 f1 , List<string> myData , float? myCpuTemp , Button b1, decimal numeric)
        {
            try
            {
                if (pause == true)
                {
                }
                else
                {
                    Trace.WriteLine("");
                    foreach (var hardwareItem in myComputer.Hardware)
                    {
                        if (hardwareItem.HardwareType == HardwareType.CPU)
                        {
                            hardwareItem.Update();
                            foreach (IHardware subHardware in hardwareItem.SubHardware)
                                subHardware.Update();

                            foreach (var sensor in hardwareItem.Sensors)
                            {
                                cpuTemp.SetValue("sensor", sensor.Value.ToString());
                                if (sensor.SensorType == SensorType.Temperature)
                                {
                                    sensor.Hardware.Update();
                                    cpuTemp.GetValue("sensor", sensor.Value.ToString());
                                    if (!f1.IsDisposed)
                                    {
                                        Thread.Sleep(1000);
                                        f1.Invoke(new Action(() => myData.Add("Cpu Temeprature --- " + sensor.Value.ToString())));
                                    }
                                    myCpuTemp = sensor.Value;
                                    //if (sensor.Value > 60)
                                    //{
                                        cpuSensorValues.Add(sensor.Value);
                                        if (cpuSensorValues.Count == 300 && sensor.Value >= (float)numeric)
                                        {
                                            float a = ComputeStats(cpuSensorValues).Item1;
                                            float b = ComputeStats(cpuSensorValues).Item2;
                                            float c = ComputeStats(cpuSensorValues).Item3;
                                            Logger.Write("********************************");
                                            Logger.Write("CPU Minimum Temperature Is ===> " + a);
                                            Logger.Write("CPU Maximum Temperature Is ===> " + b);
                                            Logger.Write("CPU Average Temperature Is ===> " + c);
                                            Logger.Write("********************************" + Environment.NewLine);                                            
                                            cpuSensorValues = new List<float?>();
                                        }
                                        b1.Enabled = true;
                                    //}
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception err)
            {
                Logger.Write("There was an exception: " + err.ToString());
            }
            return myCpuTemp;
        }

        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?>();
                                        }
                                            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;
        }

        // Returns min/max/average, ignoring null elements
        Tuple<float, float, float> ComputeStats(IEnumerable<float?> values)
        {
            float min = float.MaxValue;
            float max = float.MinValue;
            float total = 0.0f;
            int count = 0;

            foreach (var value in values)
            {
                if (value.HasValue)
                {
                    min = Math.Min(min, value.Value);
                    max = Math.Max(max, value.Value);
                    total += value.Value;
                    ++count;
                }
            }

            return Tuple.Create(min, max, total / count);
        }
    }
}

這是異常消息:

3/1/2014--9:50 PM ==> There was an exception: System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
   at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
   at System.Windows.Forms.Control.Invoke(Delegate method)
   at HardwareMonitoring.Core.cpuView(Boolean pause, CpuTemperature cpuTemp, Form1 f1, List`1 myData, Nullable`1 myCpuTemp, Button b1, Decimal numeric) in d:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Core.cs:line 69

它有點長,但它全部連接,這就是為什么我還添加了類的完整代碼。

您可以使用IsHandleCreated來檢查是否允許您調用InvokeBeginInvoke 從MSDN引用:

如果尚未創建控件句柄,則必須等到創建它之后再調用Invoke或BeginInvoke。 通常,只有在應用程序的主要表單的構造函數中創建后台線程(如在Application.Run(new MainForm())中,在顯示表單或調用Application.Run之前,才會發生這種情況。

因此,在調用Invoke之前檢查IsHandleCreated

if (f1.IsHandleCreated && !f1.IsDisposed)
{
   Thread.Sleep(1000);
   f1.Invoke(new Action(() => myData.Add("Cpu Temeprature --- " + sensor.Value.ToString())));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM