【发布时间】:2011-04-04 16:08:42
【问题描述】:
设置:带有进度条和标签的主 MDI 表单。
主窗体中的代码。
public delegate void UpdateMainProgressDelegate(string message, bool isProgressBarStopped);
private void UpdateMainProgress(string message, bool isProgressBarStopped)
{
// make sure we are running on the right thread to be
// updating this form's controls.
if (InvokeRequired == false)
{
// we are running on the right thread. Have your way with me!
bsStatusMessage.Caption = message + " [ " + System.DateTime.Now.ToShortTimeString() + " ]";
progressBarStatus.Stopped = isProgressBarStopped;
}
else
{
// we are running on the wrong thread.
// Transfer control to the correct thread!
Invoke(new ApplicationLevelValues.UpdateMainProgressDelegate(UpdateMainProgress), message, isProgressBarStopped);
}
}
子表单
private readonly ApplicationLevelValues.UpdateMainProgressDelegate _UpdateMainForm;
private void btnX_Click(object sender, EventArgs e)
{
_UpdateMainForm.BeginInvoke("StartA", false, null, null);
try
{
if(UpdateOperationA())
{ _UpdateMainForm.BeginInvoke("CompletedA", true, null, null); }
else
{ _UpdateMainForm.BeginInvoke("CanceledA", true, null, null); }
}
catch (System.Exception ex)
{
_UpdateMainForm.BeginInvoke("ErrorA", true, null, null);
throw ex;
}
}
它工作得很好,但是对于 N 个按钮或 N 个操作,我必须一次又一次地编写相同的代码。有什么方法可以概括这一点或任何其他更好的方法来更新 UI。
【问题讨论】:
标签: c# winforms user-interface asynchronous progress-bar