using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace 线程UI界面响应测试
{
    public partial class Form1 : Form
    {
        delegate void t();
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(ok));
            t.Start();
           
        }
        public void ok()
        {
            if (textBox2.InvokeRequired)//为了保证线程的安全性
            {
                MessageBox.Show("as");
                t tt = new t(a);
                textBox2.Invoke(tt);
            }
            else
                a();
        }
        public void a()
        {
           
            for (int i = 0; i <= 1000; i++)
                textBox2.Text += i;
        }
    }
}
这是我的程序,通过数数字来测试的我,我想达到的效果是textBox2记录数数字的结果,因为它是我单独开的线程,所以我就想这样子也许能解决数数字照样数,不会等到数完之后界面才能响应下一步的,因为是使用了异步委托,但是结果不是如果所料,在程序运行期间,如果我点击winform框上的其它textbox想进行填写一些其它数据的话,是不行的,会出现未响应的状态,知道那个数数字的程序执行完之后才能再其它的textbox进行输入操作!如何解决??

解决方案 »

  1.   

    MessageBox.Show("as");
    能不能不要这句
      

  2.   

      t tt = new t(a);
      textBox2.Invoke(tt);这样做你的多线程毫无意义...
      

  3.   

    我觉得是因为线程通过代理调用了UI里的组件,而ui组件是属于主线程的,所以这样一来,等于是绕了一圈之后又回来调用主线程了
      

  4.   

    试试这中方式private delegate void test(int str);
            public void ok()
            {
                test t = delegate(int tmp) { this.textBox2.Text += tmp; this.textBox2.Refresh(); };
                for (int i = 0; i <= 1000; i++)
                    this.Invoke(t, new int[] { i });
            } 
      

  5.   

    写个例子给你。就是你的代码的最终优化版本。看懂你就能学会简化的Thread写法,多线程操作,如何减少invoke时间尽早释放对界面的依赖。
    private void button6_Click(object sender, EventArgs e)
    {
        new Thread((ThreadStart)delegate
            {
                for (int i = 0; i <= 1000; i++)
                {
                    textBox2.Invoke((EventHandler)delegate { textBox2.AppendText(i.ToString()); });
                }
            }).Start();
    }
      

  6.   

    多线程控制UI 最好在页面UI的处理上加个临界点的控制标志!
      

  7.   

    只有在需要界面修改时才进入ui线程,而不是把for或者长时间的数据计算写在ui线程里。这样才不会卡。
      

  8.   

          new Thread(
                            () =>
                            {
                                writer = new StreamWriter(pipe);
                                Marshaller.PreProcess(ident, feedReader, writer);
                                writer.Flush();
                                writer.Dispose();
                            }
                            )
                            {
                                Name = ident.VendorCode + ident.FileCode + "PipeWriterThread",
                            }.Start();
      

  9.   


    他的答案基本上是对的,指出了楼主的主要毛病。
    把for计数循环写在ui更新线程里,自然会卡。但是上边的答案中,也不能完全的解决卡界面的问题。需要在for循环中加一个Thread.Sleep(),这样ui线程才有空闲时间去响应来自界面上的用户事件。