You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke(),
Problem with Treeview Scanner And MD5.
See also more references on threading:
.NET event on main thread[
^],
.NET event on main thread,
How to get a keydown event to operate on a different thread in vb.net,
Control events not firing after enable disable + multithreading.
Prathap wrote:
…To display a text in label control, I had written code in ProgressChanged event of BackgroundWorker and it works fine.
When should I use Control.Invoke
?
You need to call it each time you need to change something in UI. For example, to change the label text, you could use this method:
static void SetLabelText(Label label, string newText) {
label.Content = newText;
}
But this is something you could only call from the same UI thread. As I already explained before, you cannot call from a different thread. So, you need to call it from UI thread in all cases, but what to do in another thread?
Delegate it to the UI thread. This is how?
```cs
using System.Windows;
using System.Windows.Controls;
// ...
public partial class MyWindow : Window {
public MainWindow() {
InitializeComponent();
} //MainWindow
void SetLabelText(Label label, string newText) {
Dispatcher.Invoke(
new System.Action<label, string="">((aLabel, aText) => {
aLabel.Content = aText;
}), label, newText);
} //SetLabelText
// ...
} //class MyWindow
```
—SA