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

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. 我这样做的原因是在这个类中我获得了CPU和GPU的温度。 This is the complete class code to see it easier what im doing and how im using form1 variable: 这是完整的类代码,可以更轻松地查看我在做什么以及如何使用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);
        }
    }
}

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 . 您可以使用IsHandleCreated来检查是否允许您调用InvokeBeginInvoke Quote from MSDN: 从MSDN引用:

If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. 如果尚未创建控件句柄,则必须等到创建它之后再调用Invoke或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. 通常,只有在应用程序的主要表单的构造函数中创建后台线程(如在Application.Run(new MainForm())中,在显示表单或调用Application.Run之前,才会发生这种情况。

So check IsHandleCreated before you call Invoke : 因此,在调用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.

相关问题 为什么我总是得到InvalidOperationException? - Why im getting all the time InvalidOperationException? 我得到异常Typeload可以是什么异常? - Im getting exception Typeload what the exception can be? 我在日期明智的过滤器中从5.30 am获取记录,在时区发布 - im getting records from 5.30 am in date wise filter, issue in the time zone 如何修复System.InvalidOperationException =无法从“我的类型”类型创建服务? - How can fix System.InvalidOperationException = Unable to create service from type 'My type'? 如何解决 C# 中的“aforge 获取实时视图”问题 - How can I fix "the aforge getting real time view" problem in C# 我试图使用SolidColorBrush但得到很多无法转换类型错误如何解决它并使用SolidColorBrush? - Im trying to use SolidColorBrush but getting many Cannot convert type errors how can i fix it and use the SolidColorBrush? 如何修复 C# 中的“激活的事件时间持续时间线程异常”? - How to fix "Activated Event Time Duration Thread Exception" in C#? 每次从矩形数组中删除项目时都会出现异常 - Getting exception every time I delete an item from rectangle array 我在使用 UserManager.IsInRoleAsync() 时收到 InvalidOperationException - Im getting InvalidOperationException when using UserManager.IsInRoleAsync() 如何在C#中修复InvalidOperationException? - How to fix InvalidOperationException in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM