【问题标题】:Error trying to update TextBox via a thread [duplicate]尝试通过线程更新 TextBox 时出错 [重复]
【发布时间】:2017-11-09 02:35:10
【问题描述】:

我想在一个线程中更新 TextBox.Text,但它不起作用,我收到此错误(法语):

System.InvalidOperationException : 'Operation inter-threads non valide : le contrôle 'TextBOX' a fait l'objet d'un accès à partir d'un thread autre que celui sur lequel il a été créé。'

英文(谷歌翻译)看起来像:

System.InvalidOperationException: '无效的线程间操作:'TextBOX'控件已从创建它的线程以外的线程访问。'

我该怎么做? 这是我的代码:

using System;
using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace Ace
{
    public partial class Checker : Form
    {

        public Checker()
        {
            InitializeComponent();
        }

        private void Checker_Load(object sender, EventArgs e)
        {
            status("Checking ...");
            check();
            status("Done !");
        }

        public void check()
        {
            int threads = 10;
            var lines = File.ReadLines("test.txt");
            Parallel.ForEach(lines, new ParallelOptions { MaxDegreeOfParallelism = threads }, line =>
            {
                TextBox.Text = TextBox.Text + line + "\n"; // THIS LINE
            });
        }
    }
}

提前致谢。

【问题讨论】:

    标签: c# multithreading winforms


    【解决方案1】:

    当尝试从 UI 线程以外的另一个线程修改组件时,您必须在组件上调用 Invoke()

    变化:

    TextBox.Text = TextBox.Text + line + "\n"; // THIS LINE
    

    收件人:

    TextBox.Invoke((Delegate)(() =>
    {
        TextBox.Text = TextBox.Text + line + "\n";
    })));
    

    你也可以改变:

    TextBox.Text = TextBox.Text + line + "\n";
    

    收件人:

    TextBox.Text += line + "\n";
    

    不过,我想就您的代码向您发出警告。它不是线程安全的,并且可能会发生竞争条件。

    【讨论】:

    • 您好,感谢您的回复,但我收到此错误,如何解决?谢谢 ! Can not convert lambda expression to 'Delegate' type because it does not act as delegate type
    • 对不起。更新了我的答案,它现在应该可以工作了。忘记将表达式转换为 Delegate
    • 相同。 :/ @Bauss
    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多