winform開發時,如果要對某控件顯示的內容進行賦值,而這些內容的來源很耗時,會阻塞UI主線程,造成界面的假死,直到賦值完成界面才能接收響應。是否有方法能夠做到讓耗時的取數據操作不會影響UI的顯示和操作的流暢性呢?
可以採用線程+異步委託的方法。示列如下:
private System.Threading.Thread thread;
private delegate void InvokeDelegate();
private void Form1_Load(object sender, EventArgs e)
{
thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.startMethod));
thread.Start();
}
void ShowText()
{
this.lblShow.Text = "aaaa";
}
private void startMethod()
{
int s=System.DateTime.Now.Second;
//耗時的操作
while (true)
{
if (System.DateTime.Now.Second == s + 5)
{
break;
}
}
//耗時操作完成後,對操作UI線程(對控件賦值)
this.BeginInvoke(new InvokeDelegate(ShowText));
}