Cross operation invalid while reading property

I get this error when I try to read a property from a panel user control. The property returns the value of the text field inside the panel. How do I know a property that returns the value of a text field control from another thread? An example of my ownership code is given below. I don't care about the setter.

Here is the eaxct error message: Invalid cross-flow operation: The control '' is accessible from a stream other than the stream in which it was created.

public string Header { get { return _HeaderComboBox.Text; } set { _HeaderComboBox.Text = value; } } 
+4
source share
4 answers

MSDN Example Using BeginInvoke

Here's how I would fetch based on the Getter snippet you got:

 public string Header { get { string text = string.Empty; _HeaderComboBox.BeginInvoke(new MethodInvoker(delegate { text = _HeaderComboBox.Text; })); return text; } set { _HeaderComboBox.Text = value; } } 

There are more elegant methods, however this is a common example for you.

+6
source

To access the property, you need to transfer the call back to the user interface stream.

Before .NET 2.0, you had to call the Invoke method in the Control class to march the Text proprety call.

In .NET 2.0 and after that, if your background thread has access to the SynchronizationContext for the user interface thread, you can call the Send method to transfer the call back to the user interface.

Please note that if you do not need to wait for the result of calls (how you do it, since you want to get the result of calling the Text property), you can call BeginInvoke and Post in Control and SynchronizationContext, respectively.

+3
source

You cannot access WinForms controls in any thread other than the user interface thread, the AKA that was created, due to problems with cross-threads, race conditions, etc. To solve this problem, you need to run any commands that you want to run in the user interface thread. This can be done using the Invoke method:

 public void InvokeExample() { if (InvokeRequired) { // Invoke this method on the UI thread using an anonymous delegate Invoke(new MethodInvoker(() => InvokeExample())); return; } string header = Control.Header; } 
+2
source

You must pass your cross-thread code to a separate method, make it a delegate, and then Invoke it to Control in the thread that you want to change. You can also use closure instead of the delegate + method.

0
source

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


All Articles