更新的WinForms UI异步模式 - 需要一概而论 [英] Winforms Updating UI Asynchronously Pattern - Need to Generalize
问题描述
设置:MDI的主要形式有进度条和标签。
Setup: Main MDI form with a progress bar and a label.
code的主要形式。
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;
}
}
其工作pretty罚款,但对于N按钮或N操作我到C一遍又一遍写相同$ C $。有什么办法这个可以推广或任何其他更好的方法来更新UI。
Its working pretty fine, but for N buttons or N operations I have to write the same code again and again. Is there any way this can be generalized or any other better way to update the UI.
推荐答案
这是,如果你的操作都可以重新psented作为一个单一的委托类型$ P $真的只是一个简单的重构问题。例如:
This is really just a simple refactoring problem if your operations can all be represented as a single delegate type. e.g.:
private void RunOperationWithMainProgressFeedback(
Func<bool> operation,
string startMessage,
string completionMessage,
string cancellationMessage,
string errorMessage)
{
this._UpdateMainForm.BeginInvoke(startMessage, false, null, null);
try
{
if (operation.Invoke())
{
this._UpdateMainForm.BeginInvoke(completionMessage, true, null, null);
}
else
{
this._UpdateMainForm.BeginInvoke(cancellationMessage, true, null, null);
}
}
catch (Exception)
{
this._UpdateMainForm.BeginInvoke(errorMessage, true, null, null);
throw;
}
}
private void btnX_Click(object sender, EventArgs e)
{
this.RunOperationWithMainProgressFeedback(
this.UpdateOperationA,
"StartA",
"CompletedA",
"CanceledA",
"ErrorA");
}
虽然可以使用字典来存储参数值(如VinayC早期的答案的建议),这是没有必要的。就个人而言,我会避免这两个可读性和性能方面的原因,但情况因人而异...
While it's possible to use a dictionary to store the argument values (as suggested in VinayC's earlier answer), this isn't necessary. Personally, I would avoid it for both readability and performance reasons, but ymmv...
这篇关于更新的WinForms UI异步模式 - 需要一概而论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!