我有一個應用程序與數據庫一起運行。當我在datagridview中加載表格時,表單凍結。如何在加載表格時確保平滑加載動畫?顯示加載動畫在其他線程加載數據
我爲動畫運行兩個線程並將數據加載到表中,但動畫仍然無法正常工作。
private volatile bool threadRun;
private void UpdateTab()
{
// Create panel for animation
Panel loadingPanel = new Panel();
// Label, where the text will change
Label loadingLabel = new Label();
loadingLabel.Text = "Loading";
loadingPanel.Controls.Add(loadingLabel);
this.Controls.Add(loadingPanel);
// thread loading animation
threadRun = true;
Task.Factory.StartNew(() =>
{
int i = 0;
string labelText;
while (threadRun)
{
Thread.Sleep(500);
switch (i)
{
case 0:
labelText = "Loading.";
i = 1;
break;
case 1:
labelText = "Loading..";
i = 2;
break;
default:
labelText = "Loading...";
i = 0;
break;
}
loadingLabel.BeginInvoke(new Action(() => loadingLabel.Text = labelText));
}
});
// thread update DataGridView
Thread update = new Thread(ThreadUpdateTab);
update.Start();
}
private void ThreadUpdateTab()
{
// SQL Query...
myDataGridView1.Invoke(new Action(() => myDataGridView1.DataSource = myDataSet1.Tables[0]));
// ...
myDataGridView10.Invoke(new Action(() => myDataGridView10.DataSource = myDataSet10.Tables[0]));
threadRun = false;
}
爲什麼線程和任務的組合?選擇一個,而不是兩個。選擇TPL,恕我直言。 – Maarten
看看[在Windows窗體中將數據異步加載到我的DataTable中](http://stackoverflow.com/a/38427392/3110834)。 –
此外,如果您可能有興趣[顯示透明加載微調高於其他控件](http://stackoverflow.com/a/37473192/3110834) –