C# 使用線程同步上下文實現跨線程操作UI

SynchronizationContext 是.net提供的一套線程同步上下文其中有兩個方法實現把委託同步到線程

1.Post(異步)

2.Send(同步)

對Windows窗口消息熟悉的同學應該明白了

其函數特性類似於 SendMessage  和 PostMessage

Post 爲異步 提交了就不管了什麼時候完成什麼時候算

Send爲同步 直到委託執行完畢纔會返回

Test Winform Code

新建窗體  放一個 button 一個 listbox

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private SynchronizationContext Context { get; set; };
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Context = SynchronizationContext.Current;
            Thread t = new Thread(hTest);
            t.IsBackground = true;
            t.Start();
        }

        private void hTest(Object p)
        {
            for (int i = 0; i < 100; i++)
            {
                Context.Post((e)=>
                {
                    listBox1.Items.Add(e);
                },i);
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章