Last active
December 19, 2015 16:49
-
-
Save TheHackerDev/5986718 to your computer and use it in GitHub Desktop.
Solution for InvalidOperationException: "Cross-thread operation not valid: Control '<name>' accessed from a thread other than the thread it was created on."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void delegate MyDelegate(); // This is the delegate that will be invoked from the main thread if needed |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
MyDelegate myDelegate = new MyDelegate(myMethod); // add "myMethod()" to the delegate | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void myMethod() | |
{ | |
if (<formControl>.InvokeRequired) // This is hit if a background thread calls the surrounding method | |
{ | |
this.BeginInvoke(myDelegate); // Method definition: BeginInvoke(Delegate method, params object[] args) | |
// If called from the WPF window's code (usually "MainWindow.cs"), it will cause the GUI thread to invoke the code, allowing it to update the GUI on the GUI thread! | |
// this.BeginInvoke() and this.Invoke() are both methods that invoke a delegate from the GUI thread, as long as "this" is the WPF main window or Form element. | |
} | |
else | |
{ | |
// update the form control directly | |
<formElement>.Text = "Updated from the GUI thread."; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment