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());
}
}
}