美文网首页
WPF中UI线程频繁操作造成卡顿的处理(二)

WPF中UI线程频繁操作造成卡顿的处理(二)

作者: hhp895 | 来源:发表于2017-07-17 16:15 被阅读0次

    转载请注明原作者

    目录

    WPF中UI线程频繁操作造成卡顿的处理(一)
    WPF中UI线程频繁操作造成卡顿的处理(二)

    做法三

    做法背景

    为了避免窗口UI操作卡顿,在Windows Form开发年代,微软就提出一个解决方案,在处理UI刷新时,使用Application.DoEvents()立即更新界面。参考msdn链接https://msdn.microsoft.com/zh-cn/library/system.windows.forms.application.doevents.aspx

    预备知识

    (1)在WPF中如何改造实现DoEvents()方法。动态绘制心电图,参考链接:https://social.msdn.microsoft.com/Forums/zh-CN/febcee07-dc8b-44b4-8c0a-246daffdbe2b/wpf-?forum=wpfzhchs
    (2)网上早有大师对该种做法进行了深度分析——《从Dispatcher.PushFrame()说起》http://www.cnblogs.com/loveis715/archive/2012/01/11/2319976.html

    分析

    实际上都是通过DoEvents()方法立即实现UI的重绘,而不是等所有图片加载完毕一次性显示,那样UI界面就卡住了。
    代码:

            int i;
            List<String> strings;
            ObservableCollection<String> strs = new ObservableCollection<string>();
            private void Btn_Click(object sender, RoutedEventArgs e)
            {
                strings = loadDir(@"G:\BaiduYunDownload\风景图片壁纸\风景图片壁纸100张");
                strs.Clear();
             
                lb.ItemsSource = strs;
              
                for (int j = 0; j < strings.Count; j++)
                {
                    strs.Add(strings[j]);
                    DoEvents();
                }
            }
            public void DoEvents()
            {
                DispatcherFrame frame = new DispatcherFrame();
                Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                    new DispatcherOperationCallback(ExitFrames), frame);
                Dispatcher.PushFrame(frame);
            }
    
            public object ExitFrames(object f)
            {
                ((DispatcherFrame)f).Continue = false;
    
                return null;
            }
    

    效果

    效果与做法二一样。

    目录

    WPF中UI线程频繁操作造成卡顿的处理(一)
    WPF中UI线程频繁操作造成卡顿的处理(二)

    相关文章

      网友评论

          本文标题:WPF中UI线程频繁操作造成卡顿的处理(二)

          本文链接:https://www.haomeiwen.com/subject/wxfqkxtx.html