在其他线程中加载数据期间显示加载动画 [英] Show Loading animation during loading data in other thread

查看:25
本文介绍了在其他线程中加载数据期间显示加载动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与数据库一起运行的应用程序.当我在 datagridview 中加载表时,我的表单冻结.加载表格时如何保证加载动画流畅?

我为动画运行了两个线程并将数据加载到表中,但动画仍然不总是有效.

 private volatile bool threadRun;私有无效 UpdateTab(){//创建动画面板面板loadingPanel = new Panel();//标签,文本将发生变化的地方标签loadingLabel = new Label();loadingLabel.Text = "加载中";loadingPanel.Controls.Add(loadingLabel);this.Controls.Add(loadingPanel);//线程加载动画线程运行 = 真;Task.Factory.StartNew(() =>{int i = 0;字符串标签文本;而(线程运行){线程睡眠(500);开关 (i){案例0:labelText = "加载中.";我 = 1;休息;情况1:labelText = "加载中..";我 = 2;休息;默认:labelText = "加载中...";我 = 0;休息;}loadingLabel.BeginInvoke(new Action(() => loadingLabel.Text = labelText));}});//线程更新 DataGridView线程更新 = 新线程(ThreadUpdateTab);更新.开始();}私有无效ThreadUpdateTab(){//SQL 查询...myDataGridView1.Invoke(new Action(() => myDataGridView1.DataSource = myDataSet1.Tables[0]));//...myDataGridView10.Invoke(new Action(() => myDataGridView10.DataSource = myDataSet10.Tables[0]));线程运行 = 假;}

解决方案

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

您可以拥有

public async TaskGetDataAsync(字符串命令,字符串连接){var dt = 新数据表();使用 (var da = new SqlDataAdapter(command, connection))等待 Task.Run(() => { da.Fill(dt); });返回 dt;}private async void LoadDataButton_Click(object sender, EventArgs e){loadingPictureBox.Show();loadingPictureBox.Update();尝试{var command = @"SELECT * FROM Category";var connection = @"你的连接字符串";var data = await GetDataAsync(command, connection);dataGridView1.DataSource = 数据;}捕获(异常前){//处理异常}loadingPictureBox.hide();}

I have an application running with the database. When I load a tables in the datagridview, my form freezes. How to ensure the smooth load animation during loading tables?

I run two threads for animation and load data into the tables, but the animation still does not always work.

 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;
 }

解决方案

When the form is frozen, it means the UI thread is too busy and so even if you try to show a loading animation, it will not animate. You should load data asynchronously.

You can have an async method which returns Task<DataTable> like the GetDataAsync method which you can see in this post. Then call it in an async event handler. In the event handler, first show the loading image, then load data asynchronously and at last hide the loading image.

You can simply use a normal PictureBox showing a gif animation as loading control. Also you may want to take a look at this post to show a trasparent loading image.

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();
}

这篇关于在其他线程中加载数据期间显示加载动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆