Cross-thread operation not valid error when i get

2019-03-04 01:15发布

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.

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.

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

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.

How can I solve this issue?

1条回答
Anthone
2楼-- · 2019-03-04 01:33

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

private void myEvt_valueChnaged(string s)
{
    textBox1.Invoke(new Action(() => textBox1.Text = s));
}
查看更多
登录 后发表回答