zoukankan      html  css  js  c++  java
  • c#多线程操作Windows Forms控件

    在Windows Forms编程中涉及到的多线程操作,多个线程来更新Forms上的控件,比如textbox等。但是如果你直接在线程中更新textbox的text属性是会报错的。因为textbox是主线程创建的,子线程访问的时候就会报错。

     

    解决方案如下,建立一个Windows Forms项目,拖拉一个textbox和button就可以。

    点击button来启动线程,在线程中修改textbox的值。

    这需要使用委托类

    //启动线程

    private void button1_Click(object sender, EventArgs e)
            {
                Thread thread = new Thread(new ThreadStart(Test));
                thread.Start();
            }

    delegate void add();//委托

    public void Test()
            {
                this.BeginInvoke(new add(dd));
            }

    public void dd();//委托方法
            {
                this.textBox1.Text = "AA";
            }

    这样就可以实现。

     

    当然委托和委托方法可以再设计一下,可以输入一个参数。修改后的代码如下:

    delegate void add(string input);

            private void button1_Click(object sender, EventArgs e)
            {
                Thread thread = new Thread(new ThreadStart(Test));
                thread.Start();
            }
            public void Test()
            {
                this.BeginInvoke(new add(dd),new object[]{"我晕死了,原来这样啊"});//注意第二个参数,委托方法的参数就是在这个地方输入。委托方法中不用转换就直接是字符串了
            }

            public void dd(string input)
            {
                this.textBox1.Text = input;
            }



    再附加一个写listbox的例子。就是开启一个线程以后在listbox中写入累加的数字

    //声明线程对象

     System.Threading.Thread thread1 = null;

    //创建线程并开启

    thread1 = new Thread(startThread1);
                thread1.IsBackground = true;
                thread1.Start();

    //创建委托对象

    delegate void AddList(object o);
    //委托用的方法
            public void AddListMethod(object o)
            {
                this.listBox1.Items.Add(o.ToString());
            }
    //线程调用的方法
            public void startThread1()
            {
                for (int n = 0; n < 10000; n++)
                {

                    this.textBox1.BeginInvoke(new AddList(AddListMethod),new object[]{n});
                    System.Threading.Thread.Sleep(100);//这个地方只是为了防止线程运行太快,数字会慢慢在listbox上显示
                }
            }
  • 相关阅读:
    如何在Eclipse中彻底修改一个项目名称
    用JS在html页面实现打印功能
    关于git提交、还原使用
    maven package:Max maven Unsupported major.minor version 51.0
    Tomcat 启动报错:javax.naming.NamingException: No naming context bound to this class loader
    maven web 项目中启动报错java.lang.ClassNotFoundException: org.springframework.web.util.Log4jConfigListener
    tripwire检查文件完整性
    设置mysql表名不区分大小写
    mysql-零基础安装
    nginx-0基础安装篇
  • 原文地址:https://www.cnblogs.com/lujiangping/p/10630038.html
Copyright © 2011-2022 走看看