Skip to content

Instantly share code, notes, and snippets.

@TheHackerDev
Last active December 19, 2015 16:49
Show Gist options
  • Save TheHackerDev/5986718 to your computer and use it in GitHub Desktop.
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."
private void delegate MyDelegate(); // This is the delegate that will be invoked from the main thread if needed
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyDelegate myDelegate = new MyDelegate(myMethod); // add "myMethod()" to the delegate
}
}
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