我正在尝试将工作代码与GUI代码分离到完全不同的类中,但我希望能够向我的GUI报告进度更新和文件输出。例如,我希望我的GUI对工作类说:“从串口读取十行,但在每次接收时向我报告你所读取的内容”。目前,我最好的方法是让GUI循环十次,并在每个循环中向工作类发送一个命令来读取一件事并返回它。
我真的希望保持所有循环都在我的工作类的一侧,因为它将拥有更多信息可用(实际数据量将是可变的,工作类已经可以访问可用数据量,我希望不需要将其发送回GUI类来运行循环)。
我已经研究了BackgroundWorker,但它似乎只在长时间操作期间报告完成百分比,而没有其他内容,所以这对我没有什么帮助。有人有好主意如何实现这一点吗?
以下是一个程序的框架,希望能更好地说明我想做什么。你会如何编辑代码以满足我的要求?
GUI的主类:
我真的希望保持所有循环都在我的工作类的一侧,因为它将拥有更多信息可用(实际数据量将是可变的,工作类已经可以访问可用数据量,我希望不需要将其发送回GUI类来运行循环)。
我已经研究了BackgroundWorker,但它似乎只在长时间操作期间报告完成百分比,而没有其他内容,所以这对我没有什么帮助。有人有好主意如何实现这一点吗?
以下是一个程序的框架,希望能更好地说明我想做什么。你会如何编辑代码以满足我的要求?
GUI的主类:
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();
}
}
单独的工作类:
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++
}
}
}