以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()
{
//...
}
}