C# 异步 Winform 跨线程调用控件

方案:

1、delegate和invoke

2、delegate和BeginInvoke

区别:invoke 方法是同步

     BeginInvoke 方法是异步,另起一个线程完成工作线程

案例

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(MyThread);
            thread.Start();
            //Thread th = new Thread(MyThreadParam);
            //th.Start(new Data() { Message1="Hello", Message2="World"});
        }

        public void MyThread() 
        {
            if (this.label1.InvokeRequired)
            {
                Action<string> action = (x) => { this.label1.Text = x; };
                this.label1.Invoke(action, "Hello");
            }
            else
            {
                this.label1.Text = "World";
            }
            
        }

        //public void MyThreadParam(object obj) 
        //{
        //    var v = obj as Data;
        //    Thread.Sleep(1000 * 10);
        //    this.Text = "test";
        //}

    }

    //class Data 
    //{
    //    public string Message1 { get; set; }
    //    public string Message2 { get; set; }
    //}
}

 

 

    

posted @ 2025-06-16 13:31  市丸银  阅读(25)  评论(0)    收藏  举报