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);
        }
    }

  

posted @ 2020-12-28 11:44  NiKaFace  阅读(363)  评论(0编辑  收藏  举报