I have a MainWindow (form1) and a class called Module
In Module there is a method to create a new Backgroundworker and change a label in MainWindow. I have tried creating a public or internal method in the MainWindow code and calling it in the Module class but it doesn’t seem to work.
Can anyone help me figure this out, it’s just something which is stopping me from continuing development.
Sorry if I didn’t make things clear, if you need something cleared up let me know.
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();
}
}
MainWindow – Contains a label (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(); }
It’s a good idea not to couple the form to tightly with the module. One way to do that is to define an interface that the form implements, and have the module accept such an interface as a parameter. I’ll exemplify with some code. Let’s start with the interface:
In my example I use a
stringfor the data, but that can be whatever type you need to use. Then we implement this interface in the form:Finally the module with the BackgroundWorker:
This way the module is in no way depending on what your form class looks like (it is even unaware that it is talking to a form). In my sample I call
_receiver.SetDatafrom theRunWorkerCompletedevent handler, but it could just as well be done from aReportProgressevent handler.Also note how the form is the “driving force” here. The module does not create the form, or take any initiatives of any kind. It is simply used by the form.