C#多线程下更新UI的几种方法

1. 使用UI线程的SynchronizationContext的Post/Send方法,这种情况一般在窗体构造函数或者FormLoad中获取同步上下文

范例:

 public partial class Form1 : Form
    {
        SynchronizationContext SyncContext = null;
        public Form1()
        {
            InitializeComponent();
            //获取UI线程同步上下文
            SyncContext = SynchronizationContext.Current;
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(d=> {
                //模拟耗时操作
                Thread.Sleep(1000);
                SyncContext.Post(m => {
                    var result = m as string;
                    txtName.Text = result;
                }, "异步操作完成结果");
            });
        }
    }
public partial class Form1 : Form
    {
        SynchronizationContext SyncContext = null;
        public Form1()
        {
            InitializeComponent();
            //获取UI线程同步上下文
            SyncContext = SynchronizationContext.Current;
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(d=> {
                //模拟耗时操作
                Thread.Sleep(1000);

                SyncContext.Send(m =>
                {
                    var result = m as string;
                    txtName.Text = result;
                }, "异步操作完成结果2");
            });
        }
    }

 

2、使用Control的Invoke/BegainInvoke方法更新;

范例:

 public partial class Form1 : Form
    {
       // SynchronizationContext SyncContext = null;
        public Form1()
        {
            InitializeComponent();
            //获取UI线程同步上下文
            //SyncContext = SynchronizationContext.Current;
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(d=> {
                //模拟耗时操作
                Thread.Sleep(1000);

                if (txtName.InvokeRequired)
                {
                    txtName.Invoke(new Action<Control, string>((ctrl, data) => {
                        ctrl.Text = data;
                    }), new object[] { txtName, "异步操作完成结果3" });
                }
                else
                {
                  txtName.Text = "异步操作完成结果3";
                }
            });
        }
    }

 

posted on 2017-11-23 16:10  weicanpeng  阅读(1211)  评论(0编辑  收藏  举报

导航