Winfrom非同步更新UI
阿新 • • 發佈:2019-01-07
UI控制元件的Invoke/BegainInvoke方法更新
#region 非同步更新UI
delegate void SetTextCallback(string text);
/// <summary>
/// 點選按鈕事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAsycUi_Click(object sender, EventArgs e)
{
new Task(new Action(() => {
//線上程中更新UI(通過控制元件的.Invoke方法)
for (int i = 0; i < 50; i++)
{
Thread.Sleep(1000);
this.SetText("\r\n This text was set safely.");
}
})).Start();
//或者
//Thread thread = new Thread(new ThreadStart(this.ThreadProcSafe));
//thread.Start();
}
/// <summary>
/// 執行緒的主體方法
/// </summary>
private void ThreadProcSafe()
{
//...執行執行緒任務
//線上程中更新UI(通過控制元件的.Invoke方法)
for (int i = 0; i < 50; i++)
{
Thread.Sleep(1000);
this.SetText("\r\n This text was set safely.");
}
//...執行執行緒其他任務
}
/// <summary>
/// 更新文字框內容的方法
/// </summary>
/// <param name="text"></param>
private void SetText(string text)
{
//如果呼叫控制元件的執行緒和建立建立控制元件的執行緒不是同一個則為True
if (this.txtResulte.InvokeRequired)
{
while (!this.txtResulte.IsHandleCreated)
{
//解決窗體關閉時出現“訪問已釋放控制代碼“的異常
if (this.txtResulte.Disposing || this.txtResulte.IsDisposed)
return;
}
SetTextCallback d = new SetTextCallback(SetText);
this.txtResulte.Invoke(d, new object[] { text });
}
else
{
this.txtResulte.Text += text;
}
}
#endregion
寫到一起
private void btnAsycUi_Click(object sender, EventArgs e)
{
new Task(new Action(() =>
{
//線上程中更新UI(通過控制元件的.Invoke方法)
for (int i = 0; i < 50; i++)
{
Thread.Sleep(1000);
string upMessage = string.Format("\r\n我要更新的資訊{0}", i);
//如果呼叫控制元件的執行緒和建立建立控制元件的執行緒不是同一個則為True
while (!this.txtResulte.IsHandleCreated)
{
//解決窗體關閉時出現“訪問已釋放控制代碼“的異常
if (this.txtResulte.Disposing || this.txtResulte.IsDisposed)
return;
}
SetTextCallback setxt = new SetTextCallback(t =>
{
if (this.txtResulte.InvokeRequired == false)
{
this.txtResulte.Text += t;
}
});
this.txtResulte.Invoke(setxt, new object[] { upMessage });
}
})).Start();
}