C# 非UI线程向UI线程发送数据的两种方法

1. 使用控件的Invoke或者BeginInvoke:

public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }
 
       private void button1_Click(object sender, EventArgs e)
       {
           Task.Run(() =>
           {
               Thread.Sleep(5000);
               UpdateMessage("Hello Thread");
           });
 
       }
 
       void UpdateMessage(string message)
       {
           txtBox.BeginInvoke(new MethodInvoker(() => { txtBox.Text = message; }));
       }
   }

  

2. 使用SynchronizationContext上下文:

    public partial class Form1 : Form
    {
        readonly SynchronizationContext _uiSyncContext;
        public Form1()
        {
            InitializeComponent();
            _uiSyncContext = SynchronizationContext.Current;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                Thread.Sleep(5000);
                UpdateMessage("Hello World!");
            });

        }

        void UpdateMessage(string message)
        {
            _uiSyncContext.Post(_ => txtBox.Text = message, null);
        }
    }

  

原文地址:https://www.cnblogs.com/YourDirection/p/14200827.html