C# Invoke: Thread-Safe UI Updates
Using the Invoke method in C# allows communication between different threads, typically used to update UI controls in the UI thread. Here is a simple example.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void UpdateTextBox(string text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new MethodInvoker(delegate { textBox1.Text = text; }));
}
else
{
textBox1.Text = text;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(() =>
{
UpdateTextBox("Hello from another thread!");
});
t.Start();
}
}
In the example above, we defined an UpdateTextBox method used to update the text of the textBox1 control. In the button1_Click event, we created a new thread and called the UpdateTextBox method within it. Since updating UI controls must be done in the UI thread, we use the Invoke method in the UpdateTextBox method to ensure that the text of textBox1 is updated in the UI thread.