我正在用C#创建一个Windows表单应用程序。在当前状态下,应用程序正在报告进度,但是我需要遵循一个类设计。我需要在一个静态类中使用三种不同的静态方法。据我所知,我不能遵循这个设计。我想在我的日常工作中实现MyUtilities.ProcessList()。
就目前而言,我的(悬崖式)代码如下:
//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();
}
这个问题有通用的解决方案吗?我的想法是创建一个仅用于报告进度的类,并将引用传递给每个静态方法......但归根结底,我仍然面临着向 GUI 报告它的困难!
您可以将 BackgroundWorker 引用(或您建议的更抽象的对象)作为 ProcessList 方法的参数传递。
MyUtilities.ProcessList(backgroundWorker1);
执行此操作的标准方法是使用 IProgress
您还可以创建一个类而不是静态方法,并且该类的实例可以使用事件报告进度。
public class ListProcessor
{
public event EventHandler<ProgressChangedEventArgs> ProgressChanged;
public void Process()
{
//...code logic
if (ProgressChanged != null)
ProgressChanged(this, new ProgressChangedEventArgs(1, this));
}
}