当我从其他任务获取字符串时,跨线程操作无效错误[重复]

时间:2022-12-06 10:59:03

This question already has an answer here:

这个问题在这里已有答案:

At my code, I design a GUI that managed in one task . From the Form1 class I send parameters to method to other class at different task and get parameters from the task.

在我的代码中,我设计了一个在一个任务中管理的GUI。从Form1类我发送参数到方法到不同任务的其他类,并从任务中获取参数。

At form1 class I have myEvt_valueChnaged(string s) method that gets string s as argument - string that contain the text of textbox that send from the event at manager class - invoked from different task.

在form1类中,我有myEvt_valueChnaged(string s)方法,该方法将字符串s作为参数 - 字符串包含从管理器类的事件发送的文本框的文本 - 从不同的任务调用。

With the received string I update the textbox at the GUI as wrote here:

使用收到的字符串,我在GUI处更新文本框,如下所示:

private void myEvt_valueChnaged(string s)
{
    textBox1.Text = s;
}

with this code I get the error:

使用此代码我收到错误:

invalidoperationexception was unhandled by user code - Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.

I tried to add line at the method : var y =s; and then textBox1.Text=y; but it didn't solve it.

我试图在方法中添加一行:var y = s;然后textBox1.Text = y;但它没有解决它。

How can I solve this issue?

我该如何解决这个问题?

1 个解决方案

#1


A UI element may only be changed by the UI thread. You need to Invoke the action instead:

UI元素只能由UI线程更改。您需要调用该操作:

private void myEvt_valueChnaged(string s)
{
    textBox1.Invoke(new Action(() => textBox1.Text = s));
}

#1


A UI element may only be changed by the UI thread. You need to Invoke the action instead:

UI元素只能由UI线程更改。您需要调用该操作:

private void myEvt_valueChnaged(string s)
{
    textBox1.Invoke(new Action(() => textBox1.Text = s));
}