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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WinForm程序中,UI界面是由主线程(也称UI线程)负责更新的,其他线程不能直接修改UI界面数据,否则会抛出异常。如果需要跨线程更新UI界面数据,可以使用以下几种方法: 1. 使用Control.Invoke方法:该方法可以将UI线程委托一个方法来执行,从而实现跨线程更新UI界面数据。例如: ``` private void UpdateUI(string data) { if (this.InvokeRequired) { this.Invoke(new Action<string>(UpdateUI), data); } else { label1.Text = data; } } ``` 2. 使用Control.BeginInvoke方法:该方法与Invoke类似,但是它是异步的。它会立即返回,而不是等待委托方法执行完毕。例如: ``` private void UpdateUI(string data) { if (this.InvokeRequired) { this.BeginInvoke(new Action<string>(UpdateUI), data); } else { label1.Text = data; } } ``` 3. 使用SynchronizationContext类:该类可以在不同线程之间传递上下文信息,从而实现跨线程更新UI界面数据。例如: ``` private SynchronizationContext _syncContext; public Form1() { InitializeComponent(); _syncContext = SynchronizationContext.Current; } private void UpdateUI(string data) { _syncContext.Post(new SendOrPostCallback((obj) => { label1.Text = obj.ToString(); }), data); } ``` 以上三种方法都可以实现跨线程更新UI界面数据,根据实际情况和个人习惯选择即可。需要注意的是,跨线程更新UI界面数据是一个比较耗时的操作,如果频繁调用会对程序的性能产生影响。因此,建议仅在必要时使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值