c#

c#怎么跨线程调用窗体控件

小亿
135
2023-12-14 01:08:41
栏目: 编程语言

在C#中,如果要在一个线程中访问窗体控件,需要使用Invoke方法。下面是一个示例代码:

using System;
using System.Threading;
using System.Windows.Forms;

namespace CrossThreadAccess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 创建一个新的线程
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();
        }

        private void ThreadMethod()
        {
            // 跨线程调用窗体控件
            if (textBox1.InvokeRequired)
            {
                // 使用Invoke方法在UI线程上调用SetText方法
                textBox1.Invoke(new Action(SetText), new object[] { "Hello from another thread!" });
            }
            else
            {
                SetText();
            }
        }

        private void SetText()
        {
            textBox1.Text = "Hello from the UI thread!";
        }
    }
}

在上面的示例中,当点击button1时,会启动一个新的线程,然后在该线程中调用ThreadMethod方法。在ThreadMethod方法中,首先判断是否需要跨线程访问窗体控件。如果需要,就使用Invoke方法在UI线程上调用SetText方法,否则直接调用SetText方法。SetText方法用来更新窗体上的控件。

需要注意的是,Invoke方法的使用必须在UI线程上进行调用。如果在UI线程上调用Invoke方法,将会同步执行,而在其他线程上调用Invoke方法,将会异步执行。

0
看了该问题的人还看了