租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c#怎么跨线程调用窗体控件,c#如果跨线程调用windows窗体控件

发布时间:2023-12-14 01:08:41

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

在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方法,将会异步履行。