线程+异步委托解决因耗时长造成界面假死问题

winform开发时,如果要对某控件显示的内容进行赋值,而这些内容的来源很耗时,会阻塞UI主线程,造成界面的假死,直到赋值完成界面才能接收响应。是否有方法能够做到让耗时的取数据操作不会影响UI的显示和操作的流畅性呢?

可以采用线程+异步委托的方法。示列如下:

      private System.Threading.Thread thread;
      private delegate void InvokeDelegate();       

      private void Form1_Load(object sender, EventArgs e)
        {
            thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.startMethod));
            thread.Start();
        }

       void ShowText()
        {
            this.lblShow.Text = "aaaa";
        }

        private void startMethod()
        {
            int s=System.DateTime.Now.Second;

           //耗时的操作
            while (true)
            {
                if (System.DateTime.Now.Second == s + 5)
                {
                    break;
                }
            }

            //耗时操作完成后,对操作UI线程(对控件赋值) 
            this.BeginInvoke(new InvokeDelegate(ShowText));
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章