Linux 拨号vps windows公众号手机端

C#中怎么使用invoke

lewis 8年前 (2017-02-08) 阅读数 9 #程序编程
文章标签 c#

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门