有很多方法可以做到这一点。两个简单的选择:
(1) 在您的 UI 类中创建一个事件,例如UpdateProgress
,并以有意义的时间间隔通知该事件
例子:
private void ThreadForAnalyzingReqFile_DoWork(object sender, DoWorkEventArgs e)
{
AnotherClass processor = new AnotherClass();
processor.ProgressUpdate += new AnotherClass.ReallyLongProcessProgressHandler(this.Processor_ProgressUpdate);
processor.AVeryLongTimedFunction();
}
private void Processor_ProgressUpdate(double percentComplete)
{
this.progressBar1.Invoke(new Action(delegate()
{
this.progressBar1.Value = (int)(100d*percentComplete); // Do all the ui thread updates here
}));
}
在“另一个班级”中
public partial class AnotherClass
{
public delegate void ReallyLongProcessProgressHandler(double percentComplete);
public event ReallyLongProcessProgressHandler ProgressUpdate;
private void UpdateProgress(double percent)
{
if (this.ProgressUpdate != null)
{
this.ProgressUpdate(percent);
}
}
public void AVeryLongTimedFunction()
{
//Do something AWESOME
List<Item> items = GetItemsToProcessFromSomewhere();
for (int i = 0; i < items.Count; i++)
{
if (i % 50)
{
this.UpdateProgress(((double)i) / ((double)items.Count)
}
//Process item
}
}
}
(2) 在 上创建进度百分比字段AnotherClass
。偶尔在你的 UI 中的计时器上询问这个。