So if I understand you correctly, you're asking how to change the GUI from another thread.
This is done through a construct called the SynchronizationContext, which essentially provides a way to run code on another thread. So in your case, if you wanted to change the text of a label defined in the GUI thread, you would take the SynchronizationContext
corresponding to your GUI thread and post code to it through your other thread.
Another concept you will have to get familiar with are Tasks. A Task
is an abstraction that's functionally the same thing as a thread. Two Tasks can run at the same time. Task.Run
starts a new Task
with its workload represented by a function.
With that said, here's an example in WPF:
public class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var context = SynchronizationContext.Current;
Task.Run(() => context.Post(state => Button.Content = "Hello World!"));
}
}
Notice that even though I'm inside Task.Run
(which means I'm not on the GUI thread), I'm still able to execute code on the Button
by posting to the window's SynchroniztaionContext
.
Edit: If you're not comfortable with Task yet, and you'd like to use Thread
instead, you may be able to do that as well:
var context = SynchronizationContext.Current;
var thread = new Thread(() => context.Post(state => Button.Content = "Hello World!"));
thread.Start();