WinForm 界面异步更新数据(方式二)

在WINForm开发过程中,我们经常遇到填充比较多的数据到界面时,有时候界面卡死啦,这时候我们最好的办法是采用线程来对数据进行收集,然后再体现在界面上。

1.第一种是比较繁琐的采用异步进行操作。

创建一个委托: private delegate List<string> UpdateUIDelegate(int count);

制定委托方法: UpdateUIDelegate ui = GetData;

        //收集数据的方法

                      private List<string> GetData(int count)

                       {
                            List<string> lst = new List<string>();
                            for (int i = 0; i < count; i++)
                           {
                                 lst.Add("item"+i);
                           }
                           return lst;
                        }

异步回调:

                     private void UpdateCompleted(IAsyncResult asyncResult)
                     {
                            if (asyncResult == null) return;
                            List<string> lstDevice = (asyncResult.AsyncState as UpdateUIDelegate).EndInvoke(asyncResult);
                            //获取UI控件线程进行数据填充
                            this.button1.BeginInvoke(new Action(() => {
                                   this.button1.Text = lstDevice[lstDevice.Count - 1];
                            }));
                      }

开始调用:

                     UpdateUIDelegate ui = GetData;
                     ui.BeginInvoke(5, UpdateCompleted, ui);

2.另外一个方法就是直接用new Thead() ,但必须设置CheckForIllegalCrossThreadCalls=false;  /*不推荐使用,会有很多问题*/

转自: http://www.cnblogs.com/yisic/articles/3025234.html

原文地址:https://www.cnblogs.com/blosaa/p/3078335.html