C# 跨线程访问或者设置UI线程控件的方法

一、背景

在C#中,由于使用线程和调用UI的线程属于两个不同的线程,如果在线程中直接设置UI元素的属性,此时就会出现跨线程错误。

  image

二、问题解决方法

  • 使用控件自带的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);
    });
}
原文地址:https://www.cnblogs.com/binfire/p/5043749.html