San*_*sal 2 c# backgroundworker winforms
我有一个MainWindow(form1)和一个名为Module的类
在Module中,有一种方法可以创建一个新的Backgroundworker并在MainWindow中更改标签.我尝试在MainWindow代码中创建一个公共或内部方法,并在Module类中调用它,但它似乎不起作用.
任何人都可以帮我解决这个问题,这只是阻止我继续发展的事情.
对不起,如果我没有说清楚,如果你需要清理的东西让我知道.
Module.cs
public class Module
{
protected System.Diagnostics.PerformanceCounter cpuCounter;
BackgroundWorker cpuUThread;
private delegate void UIDelegate();
MainWindow mn;
public void runCPUUsage()
{
cpuUThread = new BackgroundWorker();
cpuUThread.DoWork += new DoWorkEventHandler(cpuUThread_DoWork);
cpuUThread.WorkerSupportsCancellation = true;
cpuUThread.RunWorkerAsync();
mn = new MainWindow();
}
void cpuUThread_DoWork(object sender, DoWorkEventArgs e)
{
cpuCounter = new System.Diagnostics.PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
try
{
mn.changeCPUULabel(getCurrentCpuUsage().ToString());
}
catch (Exception ex)
{
}
}
public double getCurrentCpuUsage()
{
return Math.Round(cpuCounter.NextValue(), 0);
}
public void disposeCpuUsage()
{
cpuUThread.CancelAsync();
cpuUThread.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
MainWindow - 包含标签(labelCPUU)
internal void changeCPUULabel(string val)
{
Dispatcher.Invoke(new UIDelegate(delegate
{
this.labelCPUU.Content = val;
}));
}
public double getCurrentCpuUsage()
{
return mod.getCurrentCpuUsage();
}
void activateCPUU(){ mod.runCPUUsage(); }
Run Code Online (Sandbox Code Playgroud)
您是否尝试从与GUI线程不同的线程更改标签?你不能这样做.但是,您可以调用Invoke任何控件,并在GUI线程到达时执行它(当然,如果GUI线程处于空闲状态,则立即执行):
// Instead of:
myMainForm.MyLabel.Text = "New Text";
// Write:
myMainForm.Invoke(new Action(() => { myMainForm.MyLabel.Text = "New Text"; }));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1944 次 |
| 最近记录: |