I am trying to separate my worker code from my GUI code into an entirely different class, but I want to be able to report back to my GUI for progress update and file output. For example, I want to have my GUI say to the worker class, “Read ten lines from the serial port, but report to me each thing you read as you receive it”. Currently my best way to do it is to have the GUI loop ten times and in each loop send a command to the worker class to read one thing and return it.
I would really prefer to keep all of the looping on the side of my worker class, since it will have more information of what is available (the actual amount of data will be variable, and the worker class already has access to the amount of data available, and I would prefer not to send this back to the GUI class to run the loop itself.
I have looked into backgroundworker but that seems to only report percentage done during a lengthy operation, and nothing else, so that would not help me much here. Does anybody have a good idea how I can accomplish this?
Below is a shell of a program to try to (hopefully) better illustrate what I want to do. How would you edit the code to do what I require?
The GUI’s main class:
class Main_Class
{
...
/* Assume in the area we have instantiated these items and placed them on the form:
* Button DoSomething: A button to do something
* TextBox ShowInfo: A text box to report something from the worker class
*/
Worker_Class timewaster = new Worker_Class();
private void buttonDoSomething_Click(object sender, EventArgs e)
{
timewaster.a_lengthy_task();
}
}
The separate worker class:
class Worker_Class
{
...//Various Setup stuff up here
void a_lengthy task()
{
int iteration = 0;
while(iteration < 10)
{
Datetime saveNOW = Datetime.Now; //lets say I report this back to the the GUI to write in that ShowInfo box
Thread.sleep(10000); //To waste time and make this lengthy
//Your code here to facilitate sending saveNOW back to the the Main_Class and display it on the ShowInfo textbox.
iteration++
}
}
}
What you need is events. If you can’t work around what’s built into the
BackgroundWorkerclass to get it to work for you, you can at least model your solution after what it does.The worker class should have a public event
IterationCompleteor whatever you want to call it. You can give it anEventArgsobject (or an object that extends EventArgs) that contains the information relevant to that iteration that the UI will need. The event can be fired after each iteration is complete (or whenever the UI modifications should take place).The UI can then subscribe to the event for all UI tasks related to that iteration.
Code sample:
Main class:
Worker class: