gpt4 book ai didi

c# - 在其他线程加载数据时显示加载动画

转载 作者:太空狗 更新时间:2023-10-30 00:49:17 25 4
gpt4 key购买 nike

我有一个与数据库一起运行的应用程序。当我在 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;
}

最佳答案

当表单卡住时,意味着 UI 线程太忙,因此即使您尝试显示加载动画,它也不会动画。您应该异步加载数据。

你可以有一个 async 返回 Task<DataTable> 的方法喜欢 GetDataAsync你可以在this post中看到的方法.然后在 async 中调用它事件处理程序。在事件处理程序中,首先显示加载图像,然后异步加载数据,然后隐藏加载图像。

您可以简单地使用普通的 PictureBox将 gif 动画显示为加载控件。您也可能想看看 this post显示透明加载图像。

enter image description here

public async Task<DataTable> GetDataAsync(string command, string connection)
{
var dt = new DataTable();
using (var da = new SqlDataAdapter(command, connection))
await Task.Run(() => { da.Fill(dt); });
return dt;
}

private async void LoadDataButton_Click(object sender, EventArgs e)
{
loadingPictureBox.Show();
loadingPictureBox.Update();
try
{
var command = @"SELECT * FROM Category";
var connection = @"Your Connection String";
var data = await GetDataAsync(command, connection);
dataGridView1.DataSource = data;
}
catch (Exception ex)
{
// Handle Exception
}
loadingPictureBox.Hide();
}

关于c# - 在其他线程加载数据时显示加载动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39140469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com