2016-08-25 66 views
1

我有一個應用程序與數據庫一起運行。當我在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; 
} 
+0

爲什麼線程和任務的組合?選擇一個,而不是兩個。選擇TPL,恕我直言。 – Maarten

+0

看看[在Windows窗體中將數據異步加載到我的DataTable中](http://stackoverflow.com/a/38427392/3110834)。 –

+0

此外,如果您可能有興趣[顯示透明加載微調高於其他控件](http://stackoverflow.com/a/37473192/3110834) –

回答

2

當表單被凍結,這意味着UI線程是太忙,所以即使你試圖表明加載動畫,它不會動畫。您應該異步加載數據。

你可以有一個async方法返回Task<DataTable>GetDataAsync方法,你可以在this post中看到。然後在async事件處理程序中調用它。在事件處理程序中,首先顯示加載圖像,然後異步加載數據,最後隱藏加載圖像。

您可以簡單地使用正常的PictureBox顯示gif動畫作爲加載控件。你也可以看看this post顯示一個透明的加載圖像。

enter image description here

public async Task<DataTable> GetDataAsync() 
{ 
    var dt = new DataTable(); 
    var cn = @"Your Connection String"; 
    var cmd = @"SELECT * FROM Category"; 
    var da = new SqlDataAdapter(cmd, cn); 
    await Task.Run(() => { da.Fill(dt); }); 
    return dt; 
} 

private async void LoadDataButton_Click(object sender, EventArgs e) 
{ 
    loadingPictureBox.Show(); 
    loadingPictureBox.Update(); 
    try 
    { 
     var data = await GetDataAsync(); 
     dataGridView1.DataSource = data; 
    } 
    catch (Exception ex) 
    { 
     //Handle Exception 
    } 
    loadingPictureBox.hide(); 
} 
+0

我發現在我的示例中,動畫凍結了dataGridView1.DataSource = data;我可以等待SQL查詢,但只要有對錶單的引用,它動畫凍結了。也許創建一個新的透明表單並在她身上顯示動畫? – DartAlex

+0

數據顯示需要時間 – DartAlex

+0

我使用了100,000條記錄,延遲時間爲250-400毫秒。如果您想要加載更多記錄,最好重新考慮想要顯示數據的方式。您需要在虛擬模式下使用分頁機制或使用數據網格視圖,並逐頁顯示數據。 –