日期:2014-05-17  浏览次数:20689 次

UI无响应,线程疑问
点击按钮之后,程序就无响应了,应该是UI假死,这种该如何做呢?
对于,多次按成不是很熟悉,望指点。。。

   private void btnStart_Click(object sender, EventArgs e)
        {
            Init();//此方法耗时较长
            this.btnStart.Enabled = false;
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(doSomeThing));
                //设置为单元线程
                newThread.SetApartmentState(ApartmentState.STA);
                newThread.Start();
                Application.DoEvents();
                Thread.Sleep(20000);
            }

        }

        private void doSomeThing()
        {
            StartImage();//此方法耗时较长
            Invoke(new myDelegate(StartImage));
        }

------最佳解决方案--------------------
本帖最后由 bdmh 于 2012-11-27 15:17:15 编辑 while (true),不死才怪,他在主线程中,把while (true)放到子线程中去
------其他解决方案--------------------
死在Thread.Sleep(20000);里,既然你用了Application.DoEvents()也可以不用多线程,

你把Thread.Sleep(20000)改为Thread.Sleep(500)就不会假死,

            while (true)            {                StartImage();                Application.DoEvents();                Thread.Sleep(500);            }
------其他解决方案--------------------
用包装好的BackgroundWork,处理下就够了


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Invoke(new MethodInvoker(delegate()
            {
                //更新UI,提示正在执行后台操作
                this.lable1.Text = "正在计算...";
            }));
            //长时间处理的代码