c# – Winforms异步更新UI模式 – 需要概括
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – Winforms异步更新UI模式 – 需要概括,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2209字,纯文字阅读大概需要4分钟。
内容图文
![c# – Winforms异步更新UI模式 – 需要概括](/upload/InfoBanner/zyjiaocheng/821/c96616a780d64c2ab804e132d3331ce7.jpg)
设置:带有进度条和标签的主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的任何其他更好的方法.
解决方法:
如果您的操作都可以表示为单个委托类型,那么这实际上只是一个简单的重构问题.例如.:
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早期的答案所示),但这不是必需的.就个人而言,我会因为可读性和性能原因而避免使用它,但是ymmv ……
内容总结
以上是互联网集市为您收集整理的c# – Winforms异步更新UI模式 – 需要概括全部内容,希望文章能够帮你解决c# – Winforms异步更新UI模式 – 需要概括所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。