简体   繁体   中英

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

The exception is on the line:

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

In the top of the class i did:

public static Form1 form1;

Then:

public Core(Form1 f)
        {
            form1 = f;

The reason im doing it this way is that in this class im getting the cpu and GPU temperatures. This is the complete class code to see it easier what im doing and how im using form1 variable:

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

This is the exception message:

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

Its a bit long but its all connected thats why i added also the complete code of the class.

You can use IsHandleCreated to check if you are allowed to call Invoke or BeginInvoke . Quote from MSDN:

If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.

So check IsHandleCreated before you call Invoke :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM