I'm creating a windows form application in C#. In it's current state, the application is reporting progress, however I have a class design I need to follow. I need to make use of three different static methods within a static class. To my knowledge I can't follow this design. I want to implement MyUtilities.ProcessList() in my do work routine.
As it stands, my (cliffnoted) code is the following:
//form load
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
//calls the BG worker function
private void startWork()
{
backgroundWorker1.RunWorkerAsync();
}
// update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// update progressbar
progressBar1.Value = e.ProgressPercentage;
}
//the big crunch work
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
/*
This isn't my current code, but it should give an idea of my execution and how I currently report progress
There is no issues with my existing code in this section, this is just dummy code.
*/
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(100);
percent = (i / 5)
//20% of the full end task is done.
backgroundWorker1.ReportProgress(percent);
}
//How do I access the report progress method if I'm in a different class???
MyUtilities.ProcessList();
}
Is there a common solution to this problem? My idea is to create a class just for reporting progress, and pass the reference to each static method... but at the end of the day, I still face the difficulty of reporting it to the GUI!
You can pass your BackgroundWorker reference (or a more abstract object as you suggest) as an argument of ProcessList method.
MyUtilities.ProcessList(backgroundWorker1);
A standard way to do this is to use an IProgress< T> but it's generaly used in async code.
You could also make a class instead of a static method and an instance of the class can report Progress using an event.
public class ListProcessor
{
public event EventHandler<ProgressChangedEventArgs> ProgressChanged;
public void Process()
{
//...code logic
if (ProgressChanged != null)
ProgressChanged(this, new ProgressChangedEventArgs(1, this));
}
}