Cross-thread operation the easy way
If you are struggling with updating a UI component on either a Windows Forms or a WPF control, element from a background thread, DO NOT (in Win Forms) set CheckForIllegalCrossThreadCalls = false;
This is the wrong thing to do and you can easily introduce strange errors and poor performance into your application.
At first just accept the syntax, eventually you will come to understand what it means.
Any code that causes an illegal cross-thread operation error simply put it between the following code:
WinForms:
this.Invoke(new Action(delegate()
{
//Code here
}));
WPF:
Dispatcher.Invoke(new Action(delegate()
{
//Code here
}));
Both do exactly the same thing. Try it and see if it works, you will only get errors if the window has not been created yet, so make sure you wait a second or 2 after InitializeComponent has been called, if you get errors about the Windows handle not been created you can actually force this in .NET by doing:
IntPtr x = this.Handle;
This explanation of what this code is doing may well be incorrect but in my mind it makes sense please feel free to email me and I will update this explanation…
this.Invoke( – This means add a task to the UI thread, i.e. queuing this bit of code into the UI threads task list. So that whatever code is applied will run on the UI thread. In a way you are interrupting the UI thread and quickly placing in some code to run on it.
new Action( creates a delegate – think of this as a pointer to a function. This takes a function as its argument, but we want to declare the code inline for programming convenience rather than pointing it to an actual function, the end result is the same but in code is much better.
you can declare a function inline by stating delegate(){}; (not on its own)
Therefore the final syntax is
this.Invoke(new Action(delegate()
{
}
));
Easy really. I believe this probably only works on newer versions of C#.
Comments welcome.
Good Day im fresh on here. I came accross this site I have found It incredibly accessible & it has helped me tons. I hope to contribute & guide others like it has helped me.
Cheers, Catch You Around