以processbar为例,在不同线程中访问form1中的进度条。
开启线程,并在线程中调用进度条控件
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BtnUpdate_Click(object sender, EventArgs e)
{
//AutoUpdate ud = new AutoUpdate();
//ud.UpdateMain();
new System.Threading.Thread(new System.Threading.ThreadStart(Update)).Start();
}
public void Update()
{
AutoUpdate ud = new AutoUpdate(); //调用新的类
ud.onAutoUpdateProgress += new AutoUpdate.dAutoUpdateProgress(ud_onAutoUpdateProgess);
ud.UpdateMain(); //线程中的主代码
}
//同步更新UI
void ud_onAutoUpdateProgess(long total, long current)
{
if(this.InvokeRequired)
{
this.Invoke(new AutoUpdate.dAutoUpdateProgress(ud_onAutoUpdateProgess), new object[] { total, current });
}
else
{
this.progressBar.Maximum = (int)total;
this.progressBar.Value = (int)current;
}
}
}
在线程调用的类中,使用以下两行代码完成控件代理
public class AutoUpdate
{
//委托
public delegate void dAutoUpdateProgress(long total, long current);
//事件
public event dAutoUpdateProgress onAutoUpdateProgress;
public void UpdateMain()
{
//...
}
}
本文介绍了一种在C#中实现跨线程更新UI的方法。通过创建一个独立的类来处理后台线程中的更新逻辑,并利用委托和事件机制安全地更新主线程中的进度条控件。

5723

被折叠的 条评论
为什么被折叠?



