我创建了一个 Winforms 应用程序,它使用 Open Hardware Monitor 使用 Live Charts 以仪表格式显示 PC 温度。我知道以下代码会导致 UI 在图表更新时变得无响应,但我无法弄清楚如何实现任何形式的线程来处理此问题,或者如何更改我对应用程序的编码方式以保持用户界面响应。计时器将每两秒计时一次,以获取值并更新仪表。
添加到项目中的参考是:
- OpenHardwareMonitorLib
- LiveCharts.Winforms + 依赖项
请参阅下面的代码,任何建议将不胜感激。
UserControls.TempGauge
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
namespace PCDashboard.UserControls
{
public partial class TempGauge : UserControl
{
public TempGauge(string name)
{
try
{
//Initialize
InitializeComponent();
//Gauge Properties
this.Name = name;
gaugeName.Text = name;
gauge.Uses360Mode = true;
gauge.From = 0;
gauge.To = 110;
gauge.Value = 0;
gauge.HighFontSize = 60;
gauge.Base.Foreground = System.Windows.Media.Brushes.White;
gauge.InnerRadius = 0;
gauge.GaugeBackground = Classes.Colours.Blue;
}
catch (Exception)
{
}
}
}
}
主窗体
using OpenHardwareMonitor.Hardware;
using PCDashboard.Classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PCDashboard.Forms
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
try
{
GetSystemTemps(false);
timer.Enabled = true;
}
catch (Exception)
{
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void GetSystemTemps(bool UpdateGauge)
{
try
{
UpdateVisitor updateVisitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
//Which components to read?
computer.CPUEnabled = true;
computer.GPUEnabled = true;
computer.MainboardEnabled = true;
computer.RAMEnabled = true;
computer.Accept(updateVisitor);
foreach (IHardware hardware in computer.Hardware)
{
foreach (ISensor sensor in hardware.Sensors.Where(
x => x.SensorType == SensorType.Temperature))
{
if (UpdateGauge)
{
UserControls.TempGauge tempGauge =
((UserControls.TempGauge)gaugeContainer
.Controls[sensor.Name]);
if (tempGauge != null)
{
tempGauge.gauge.Value = Math.Round(
double.Parse(sensor.Value.ToString()), 0);
}
}
else
{
UserControls.TempGauge tempGauge =
new UserControls.TempGauge(sensor.Name);
gaugeContainer.Controls.Add(tempGauge);
}
}
}
computer.Close();
}
catch (Exception)
{
}
}
private void timer_Tick(object sender, EventArgs e)
{
try
{
GetSystemTemps(true);
}
catch (Exception)
{
}
}
}
}