如何在静态方法上使用invoke ?

本文关键字:invoke 静态方法 | 更新日期: 2023-09-27 18:03:13

我有这样一个类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenHardwareMonitor.Hardware;
using System.Diagnostics;
using System.Management;
using System.Windows.Forms;
using DannyGeneral;
namespace HardwareMonitoring
{
    class Hardware
    {
        public static Form1 form1;
        public static CpuTemperature settings;
        public static ManagementObjectSearcher searcher;
        public Hardware(Form1 f1)
        {
            form1 = f1;
            settings = new CpuTemperature(new Dictionary<string, string>
            {
                { "/intelcpu/0/temperature/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9/+NX6N3/TJm9/5f/01fw1+fosnv+A/+OlfS37/jZ/s/Lpv9fff6Ml/NTef/yZPnozc5679b+i193//TQZ+/w2Dd+P9/sZeX/67v/GTf/b3iP3u4/ObBL//73+i+f039+D8Zk/+xz/e/P6beu2TQZju8yH8f6OgzcvPv/U3/Rb8+z/0f/9b/+yfaOn8079X6fr6Cws7ln/iHzNwflPv99/wyS/+xY4+v/evcJ+733+jJ5//Cw7/4ndy9Im3+U2e/Fbnrk31C93vrt/fyPvdb+N//hsF7/4/AQAA//9NLZZ8WAIAAA==" },
                { "/intelcpu/0/load/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9++mpwcv/md/9df89egZ/xX/ym/5y/4D37618Lv7ya//u+58+u+5d9/z7/5t/w9/6u5fP5bH/6av+eTkXyefXxp26ONaf/v/dG/sf39D/rvnv4e5vc/0IP56/waK/vuHzf5I38P8/tv+mv8Rbb9f0pwTF9/zr/1X9vP/8I//+/6Pf7Z30N+/zdf/HX29zd/859q4aCNP5b//U+U3/+7f+zXOjZwfqvDX/V7/o9/vPz+a1G/pv0f+fGlhfk7eZ//N3/0v28//5X0u/n8Cxq7+f1X/tHft20A5x8a/W5/02+BP36Nf+j/nv8XfzrT+c2//Ob4p3+vktvUhNs/+xcWikP6e/4T/5jS5M8/sL8vP/5ff49f/Ivl9//sHzv6PX/vXyG//9R/94/9HuZ34P/5vyC//3W/5e/1exa/k+Bw4bUBnU2bP4Xg/1bn0uafeTH6PatfKL//N3/0t2y/gG9+/8+IzqYNxmU+/+jwX7afY67/nwAAAP//GYSA31gCAAA=" },
            });
            searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration");
            videoCardType("ati", "nvidia", f1.lb4());
        }
        public static void cpuView(bool pauseContinue, List<string> myData, ListBox lb1, Button bt1, float? tempcpuv)
        {
            if (pauseContinue == true)
            {
            }
            else
            {
                Computer myComputer = new Computer();
                myComputer = new Computer(settings) { CPUEnabled = true };
                myComputer.Open();
                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)
                        {
                            settings.SetValue("sensor", sensor.Value.ToString());
                            if (sensor.SensorType == SensorType.Temperature)
                            {
                                sensor.Hardware.Update();
                                settings.GetValue("sensor", sensor.Value.ToString());
                                //label17.Text = sensor.Value.ToString() + "c";//String.Format("{0} Temperature = {1}c", sensor.Name, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value");
                                myData.Add("Cpu Temeprature --- " + sensor.Value.ToString());
                                lb1.DataSource = null;
                                tempcpuv = sensor.Value;
                                if (sensor.Value > 60)
                                {
                                    Logger.Write("The Current CPU Temperature Is ===> " + sensor.Value);
                                    bt1.Enabled = true;
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        public static void gpuView(bool pauseContinue, List<string> myData, ListBox lb1, Button bt1, float? tempgpuv, Label lb4)
        {
            if (pauseContinue == true)
            {
            }
            else
            {
                Computer computer = new Computer();
                computer.Open();
                computer.GPUEnabled = true;
                foreach (var hardwareItem in computer.Hardware)
                {
                    if (videoCardType("ati", "nvidia",lb4) == 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(() => myData.Add("Gpu Temeprature --- " + sensor.Value.ToString())));
                                        lb1.DataSource = null;
                                        //sensor.Value.ToString() + "c";
                                        tempgpuv = sensor.Value;
                                        //label8.Visible = true;
                                    }
                                    if (sensor.Value > 60)
                                    {
                                        Logger.Write("The Current Nvidia GPU Temperature Is ===> " + sensor.Value);
                                        bt1.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)
                                    {
                                        tempgpuv = sensor.Value;
                                        //label8.Visible = true;
                                    }
                                    if (sensor.Value > 60)
                                    {
                                        Logger.Write("The Current Ati GPU Temperature Is ===> " + sensor.Value); // to check when writing to the log each second its writing the snesor value a lot of time in gpu and cpu
                                        // to check why to make that it will write every second or every n times once. and not a lot of times maybe to change the logger write place not in loop ?
                                        bt1.Enabled = true;
                                    }
                                    form1.Select();
                                }
                            }
                        }
                    }
                }
            }
        }
         public static bool videoCardType(string ati , string nvidia, Label lb4)
        {
            bool atiNvidia = false;
            string graphicsCard = string.Empty;
            foreach (ManagementObject mo in searcher.Get())
            {
                foreach (PropertyData property in mo.Properties)
                {
                    if (property.Name == "Description")
                    {
                        graphicsCard = property.Value.ToString();
                    }
                }
            }
            if (graphicsCard.Contains("NVIDIA") || graphicsCard.Contains("nvidia"))
            {
                atiNvidia = true;
                string toPrintNvidia = nvidia;
                if (graphicsCard.ToUpper().Contains(toPrintNvidia.ToUpper()))
                {
                    int startingIndex = graphicsCard.ToUpper().IndexOf(toPrintNvidia.ToUpper());
                    graphicsCard = graphicsCard.Substring(startingIndex, toPrintNvidia.Length);
                }
                lb4.Text = graphicsCard;
                return atiNvidia;
            }
            if (graphicsCard.Contains("ATI") || graphicsCard.Contains("ati"))
            {
                atiNvidia = false;
                string toPrintAti = ati;
                if (graphicsCard.ToUpper().Contains(toPrintAti.ToUpper()))
                {
                    int startingIndex = graphicsCard.ToUpper().IndexOf(toPrintAti.ToUpper());
                    graphicsCard = graphicsCard.Substring(startingIndex, toPrintAti.Length);
                }
                lb4.Text = graphicsCard;
                return atiNvidia;
            }
            return atiNvidia;
        }
    }
}

在类里面我有这个方法/函数:

public static void gpuView

在这个方法中,我有这一行,我想调用:

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

但是在这个我得到错误:

错误1关键字'this'在静态属性static中无效方法,或静态字段初始化项

如果我删除静态,只使函数公开,然后我得到错误的调用:

错误1 '硬件监控。"硬件"不包含定义对于'Invoke',没有扩展方法'Invoke'接受first类型为"硬件监控"的参数。硬件可以找到(你吗?缺少using指令或程序集引用?)

错误2非静态字段需要对象引用,方法,或者属性'HardwareMonitoring.Hardware.gpuView(bool,System.Collections.Generic。列表、System.Windows.Forms.ListBoxSystem.Windows.Forms。按钮,浮动?, System.Windows.Forms.Label)

DoWork事件:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (true)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)
                    {
                        soundPlay = true;
                        blinking_label();
                        NudgeMe();
                    }
                    else
                    {
                        soundPlay = false;
                        stop_alarm = true;
                    }
                    data = new List<string>();
                    Hardware.cpuView(pauseContinueDoWork, data, listBox1, button1, tempCpuValue);
                    Hardware.gpuView(pauseContinueDoWork, data, listBox1, button1, tempGpuValue, label4);
                    listBox1.DataSource = data;
                    listBox1.Invalidate();
                }
            }
        }
And the two listBox events:
    private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
            {
                e.ItemHeight = 21;
            }
            private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
            {
                if (e.Index == -1)
                {
                }
                else
                {
                    ColorText.ColorListBox(data, e);
                }
            }
And the ColorText class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Drawing;
    using System.Windows.Forms;
    namespace GatherLinks
    {
        class ColorText
        {

            public static void Texts(RichTextBox box, string text, Color color)
            {
                box.SelectionStart = box.TextLength;
                box.SelectionLength = 0;
                box.SelectionColor = color;
                box.AppendText(text);
                box.SelectionColor = box.ForeColor;
            }
            public static void ColorListBox(List<string> data, DrawItemEventArgs e)
            {
                string strLeft = null;
                string strMid = "---";
                string strRight = null;
                if (data[e.Index].Contains(strMid))
                {
                    int index = data[e.Index].IndexOf(strMid);
                    strLeft = data[e.Index].Substring(0, index);
                    strRight = data[e.Index].Substring(index + strMid.Length);
                }
                using (Font f = new Font(FontFamily.GenericSansSerif, 16, FontStyle.Regular))
                {
                    float startPos;
                    e.Graphics.DrawString(strLeft, f, Brushes.Red, e.Bounds.X, e.Bounds.Y);
                    startPos = e.Graphics.MeasureString(strLeft, f).Width;
                    e.Graphics.DrawString(strMid, f, Brushes.Black, e.Bounds.X + startPos, e.Bounds.Y);
                    startPos = e.Graphics.MeasureString(strLeft + strMid, f).Width;
                    e.Graphics.DrawString(strRight, f, Brushes.Green, e.Bounds.X + startPos, e.Bounds.Y);
                }
            }
        }
    }

在Form1 load事件中我做了:

h = new Hardware(this);
backgroundWorker1.RunWorkerAsync();

如何在静态方法上使用invoke ?

From msdn docs

Executes the specified delegate on the thread that owns the control's underlying window handle.

为了使用Invoke,你需要一个控件。为什么不用lbl1呢?调用或传入的其他控件之一?