zoukankan      html  css  js  c++  java
  • 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";
                    }
                });
            }
        }
  • 相关阅读:
    Android MediaScanner 详尽分析
    你要清楚的东西
    Centos下搭建Apache+mysql+php
    Centos 安装MySQL全过程
    sdk platform tools is missing please user the sdk manager to install it
    尚书令
    文字
    ubuntu下mysql配置
    学习Android开发,配置环境,
    Sphinx全文索引安装教程
  • 原文地址:https://www.cnblogs.com/weicanpeng/p/7885421.html
Copyright © 2011-2022 走看看