【发布时间】:2018-01-29 18:25:18
【问题描述】:
我尝试通过
访问标签label.Text = "Some Text";
来自一个线程。但我无法访问。 我不能将标签定义为公共的,因为它在 Windows 窗体系统中。例如 Form1.cs 是包含所有程序的类,在另一个选项卡中是 Form1.css[Design]。
所以。
如何从 Form1.css 访问 Form1.css[Design] 中的标签。
PS:我还是 C# 的初学者。
这就是全部代码
using System;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace BatteryAnalyser
{
public partial class Form1 : Form
{
Thread batteryThread = new Thread(BatteryStatusThread);
int toogle = 0;
public Form1()
{
InitializeComponent();
}
static int GetBatteryStatus() // THIS PART WORKS TO GET THE STATUS OF THE BATTERY
{
int batteryStatusValue;
PowerStatus p = SystemInformation.PowerStatus;
batteryStatusValue = (int)(p.BatteryLifePercent * 100);
Debug.WriteLine("Get Battery Status Method called. Battery percentage = " + batteryStatusValue);
return batteryStatusValue;
} // GOOD CODE WORKS
public static void BatteryStatusThread() //THIS IS THE THREAD THAT SHOULD UPDATE THE BATTERY PERCENTAGE IN THE LABEL VIA labelBattery.Text
{
Debug.WriteLine("BatteryThread entered");
while (true)
{
int batteryVal = GetBatteryStatus();
labelBattery.Text = batteryVal.ToString(); //THIS PART DOSNT RESPOND
Thread.Sleep(1000);
}
}
private void calculatingToogle_Click(object sender, EventArgs e)
{
//MessageBox.Show(toogle.ToString());
labelBattery.Text = "It works from here because its a non static method";
if (toogle == 0)
{
toogle = 1;
calculatingToogle.Text = "Stop";
try
{
batteryThread.Start();
//Debug.WriteLine("Thread.Start activated");
}
catch (Exception exc)
{
//MessageBox.Show("Battery Thread start " + e.ToString());
}
try
{
batteryThread.Resume();
//Debug.WriteLine("Thread.Resume activated");
}
catch (Exception exc)
{
//MessageBox.Show("Battery Thread Resume " + e.ToString());
}
return;
}
else if (toogle == 1) ;
{
toogle = 0;
calculatingToogle.Text = "Start";
try
{
batteryThread.Suspend();
//Debug.WriteLine("Thread.Suspend activated");
}
catch (Exception exc)
{
//MessageBox.Show("Battery Thread Suspend " + e.ToString());
}
}
}
}
}
我发现我无法更改标签,因为它是一个静态线程。但在非静态方法中它工作正常。我该如何解决?
【问题讨论】:
-
查看右侧“相关”栏中的链接。
-
您不应该从另一个线程访问 WinForms 控件。设计存在根本缺陷。如何检查你是否在正确的线程上?使用
Control.InvokeRequired。您可以使用Control.BeginInvoke和Control.Invoke等多种方式进行编组。
标签: c# multithreading winforms label