How to access a control from another thread?

How can I access the control from a stream other than the stream on which it was created, avoiding cross-flow error?

Here is my sample code for this:

private void Form1_Load(object sender, EventArgs e) { Thread t = new Thread(foo); t.Start(); } private void foo() { this.Text = "Test"; } 
+4
source share
4 answers

There is a well-known template, and it looks like this:

 public void SetText(string text) { if (this.InvokeRequired) { this.Invoke(new Action<string>(SetText), text); } else { this.Text = text; } } 

And there is also a quick dirty fix, which I do not recommend using except to test it.

 Form.CheckForIllegalCrossThreadCalls = false; 
+11
source

You should check the Invoke method.

+2
source

Check - How to make secure calls for Windows Forms Controls

 private void foo() { if (this.InvokeRequired) { this.Invoke(() => this.Text = text); } else { this.Text = text; } } 
+1
source

You should check with the InvokeRequired method to find out if you are in one thread or another thread.

MSDN link: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx

Your method can be reorganized this way.

 private void foo() { if (this.InvokeRequired) this.Invoke(new MethodInvoker(this.foo)); else this.Text = "Test"; } 
+1
source

Source: https://habr.com/ru/post/1342959/


All Articles