线程中更新ui- SynchronizationContext-Post/Send方法-简单实验

1.通过UI线程的SynchronizationContext的Post/Send方法更新

1.1.概要

// 定义
SynchronizationContext m_SyncContext = null;
        public Form1()
        {
            //赋值
            m_SyncContext = SynchronizationContext.Current;
        }
private void button3_Click(object sender, EventArgs e)
        {
            //定义线程
            Task t = new Task(() =>
            {
                    // 更新方式
                    m_SyncContext.Post(setStr, str);
            });
            t.Start();
        }
        // 更新ui的函数
        private void setStr(Object o) {
            textBox1.AppendText("\r\n"+o.ToString());
        }

1.2代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp12
{
    public partial class Form1 : Form
    {
        SynchronizationContext m_SyncContext = null;
        SerialPort serialPort1;
        public Form1()
        {
            InitializeComponent();
            m_SyncContext = SynchronizationContext.Current;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1 = new SerialPort(textBox2.Text);
                serialPort1.Open();
                setStr("\n启动成功");
            }
            catch (Exception ex) {
                setStr(ex.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] bf = new byte[1000];
            serialPort1.Read(bf, 0, 1000);
            String str = Encoding.ASCII.GetString(bf);
            textBox1.AppendText("\n"+str);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Task t = new Task(() =>
            {
                while (true) {
                    byte[] bf = new byte[1000];
                    serialPort1.Read(bf, 0, 1000);
                    String str = Encoding.ASCII.GetString(bf);
                    //textBox1.AppendText("\n" + str);
                    m_SyncContext.Post(setStr, str);
                }
            });
            t.Start();
        }
        private void setStr(Object o) {
            textBox1.AppendText("\r\n"+o.ToString());
        }
    }
}

引用参照:C# Winform 跨线程更新UI控件常用方法汇总

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值