阅读量:1
在C#中使用Invoke方法可以在不同线程之间进行通信,通常用于在UI线程中更新UI控件。下面是一个简单的示例:
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(); } }
在上面的示例中,我们定义了一个UpdateTextBox方法,该方法用于更新textBox1控件的文本。在button1_Click事件中,我们创建了一个新线程,并在其中调用UpdateTextBox方法。由于更新UI控件必须在UI线程中进行,因此我们在UpdateTextBox方法中使用Invoke方法来确保在UI线程中更新textBox1的文本。