youyiyang 2021-07-29 13:52 采纳率: 74.2%
浏览 42
已结题

这段代码为什么不能运行?子线程访问UI主线程的控件不能执行



```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace invoke1
{
    public delegate void MyInvoke(string str);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        

        private void button9_Click(object sender, EventArgs e)
        {
            //_myInvoke = new MyInvoke(SetText);
            //CheckForIllegalCrossThreadCalls = false;
            Thread t = new Thread(new ThreadStart(fun));
            t.Start();
        }

        private void fun()
        {
            //_myInvoke("dddd");
            SetText("ddd");
        }
        private void SetText(string s)
        {
            if (textBox6.InvokeRequired)
            {
                MyInvoke _myInvoke = new MyInvoke(SetText);
                this.Invoke(_myInvoke, new object[] { s });
            }
            else
            {
                this.textBox6.Text = s;
            }
        }
    }


}

```

  • 写回答

3条回答 默认 最新

  • Aganstrong 2021-07-29 16:08
    关注

    线程内委托执行textBox的修改比较好

    private delegate void dvg(string s);
    
    private void ceshiThread(Object obj)
    {
        textBox1.Invoke(new dvg((s) => {
                textBox1.Text = s;
        }), new object[] { "你需要赋值的字符串" });
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        Thread th = new Thread(ceshiThread);
        th.IsBackground = true;
        th.Start();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月7日
  • 已采纳回答 7月30日
  • 创建了问题 7月29日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改