我正在用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报告它的困难!
答案 0 :(得分:1)
您可以将BackgroundWorker引用(或者您建议的更抽象的对象)作为ProcessList方法的参数传递。
MyUtilities.ProcessList(backgroundWorker1);
执行此操作的标准方法是使用IProgress< T>,但它通常用于异步代码。
您也可以创建一个类而不是静态方法,并且该类的实例可以使用事件报告Progress。
public class ListProcessor
{
public event EventHandler<ProgressChangedEventArgs> ProgressChanged;
public void Process()
{
//...code logic
if (ProgressChanged != null)
ProgressChanged(this, new ProgressChangedEventArgs(1, this));
}
}