溫馨提示×

C#中怎么使用invoke

c#
小億
133
2024-02-19 09:26:21
欄目: 編程語言

在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的文本。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女