• 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";
                    }
                });
            }
        }
  • 相关阅读:
    QSPI
    温度标准
    minigui占用空间的情况
    引导页的展示
    Xcode6.0以后SVN的配置
    【转】iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD
    SDWebImage最新使用
    OC设计模式
    Objective-c的@property 详解
    iOS开发时间戳与时间,时区的转换,汉字与UTF8,16进制的转换
  • 原文地址:https://www.cnblogs.com/weicanpeng/p/7885421.html
Copyright © 2020-2023  润新知