日期:2014-05-18  浏览次数:20902 次

winform UI更新时卡的问题
RT
这个问题已经困扰我很久了,查了很多资料,还是没解决。。。
是这样的,我做一个知识库管理编辑器,用的是RichTextBox,导入文件用的是LoadFile方法。
当LoadFile加载大数据(比如:100M)时,为了友好响应,所以会弹出WaitForm,可是WaitForm却不能响应,代码如下:
C# code

/// <summary>
        private delegate void LoadFileDelegate(string path, RichTextBoxStreamType streamType);

        /// 加载文件
        /// </summary>
        /// <param name="path"></param>
        public bool LoadFile(string path)
        {
            WaitForm waitForm = null;

            bool isSuc = true;
            RichTextBoxStreamType streamType = RichTextBoxStreamType.RichText;

            try
            {
                Thread thread = new Thread(new ThreadStart(delegate()
                {
                    System.Threading.Thread.Sleep(200);
                    LoadFileDelegate loadFileDelegate = new LoadFileDelegate(LoadFile);
                    loadFileDelegate.BeginInvoke(path, streamType,
                    result =>
                    {
                        LoadFileDelegate loadFileDelegate2 = (LoadFileDelegate)result.AsyncState;
                        loadFileDelegate2.EndInvoke(result);
                        if (waitForm != null)
                        {
                            waitForm.Invoke(new MethodInvoker(delegate()
                            {
                                waitForm.Close();
                                waitForm.Dispose();
                            }));
                        }
                    }, loadFileDelegate);
                }));
                thread.Start();

                waitForm = new WaitForm("正在导入文件,请稍侯...");
                waitForm.ShowDialog();
                //txtEditor.LoadFile(path, streamType);
            }
            catch (Exception ex)
            {
                LogFile.WriteLogInfo(ex.ToString(), "编辑器【加载文件】失败!");
                isSuc = false;
            }
            return isSuc;
        }
        private void LoadFile(string path, RichTextBoxStreamType streamType)
        {
            this.BeginInvoke(new MethodInvoker(delegate()
            {
                txtEditor.LoadFile(path, streamType);
            }));
        }



------解决方案--------------------
System.Threading.Thread.Sleep(200) 这是做什么呢?好奢侈地浪费200毫秒啊!

既然使用异步调用 loadFileDelegate,你在外边又套用一个线程干什么呢?难道额外管理一个线程不占用时间?

你的waitForm.ShowDialog();工作在主线程,自然就把主线程卡死了。
------解决方案--------------------
如果“为了友好响应”,可以看看msdn上关于 backgroundworker 之类的代码。
------解决方案--------------------
1,把外头的蛇足线程去掉
2,第二个方法改成这样:

C# code

        private void LoadFile(string path, RichTextBoxStreamType streamType)
        {
            txtEditor.LoadFile(path, streamType);
        }

------解决方案--------------------
为什么要用多线程那么麻烦呢。。为什么要一次load 100m呢。。分页load,每次几十100k,秒杀多线程。。连wait都省了。。
------解决方案--------------------
我覺得你應該使用 AutoVue 20.2,這個能讀幾百種文檔,況且是java的api,速度很快,不假死
------解决方案--------------------
探讨

引用:
我覺得你應該使用 AutoVue 20.2,這個能讀幾百種文檔,況且是java的api,速度很快,不假死


能提供个免费的吗