C# 跨線程訪問或者設置UI線程控件的方法

1、背景

在C#中,因爲使用線程和調用UI的線程屬於兩個不一樣的線程,若是在線程中直接設置UI元素的屬性,此時就會出現跨線程錯誤。this

  image

 

2、問題解決方法

 

  • 使用控件自帶的Invoke或者BeginInvoke方法。
ThreadPool.QueueUserWorkItem(ar =>
{
    this.button1.Invoke(new Action(() =>
    {
        this.button1.Text = "aa";
    }));
});

 

 

  • 使用線程的同步上下文 SynchronizationContext
private SynchronizationContext _syncContext = SynchronizationContext.Current;

private void button1_Click(object sender, EventArgs e)
{
    ThreadPool.QueueUserWorkItem(ar =>
    {
        _syncContext.Post(p =>
        {
            this.button1.Text = "aa";
        }, null);
    });
}
相關文章
相關標籤/搜索