首先通过Nuget安装包System.Reactive.

ReactiveX项目 Url: https://github.com/Reactive-Extensions/Rx.NET

 public partial class ZSerialportForm : Form
{
private SerialPort sp;
private byte[] buffer = new byte[];
// 定义ReactiveX对象
private IScheduler scheduler = new DispatcherScheduler(Dispatcher.CurrentDispatcher);
public ZSerialportForm()
{
InitializeComponent();
} private void ZSerialportForm_Load(object sender, EventArgs e)
{
cbb_serials.Items.AddRange(SerialPort.GetPortNames());
if (cbb_serials.Items.Count > )
cbb_serials.SelectedIndex = ; btn_send.Enabled = false;
} public static string GetHexStr<T>(T[] data, int len = -, string separator = " ")
where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
{
string hex = "";
int upper = data.Length;
if (len != -) upper = len;
for (int i = ; i < upper; i++)
{
hex += data[i].ToString("x2", new NumberFormatInfo());
hex += separator;
} hex = hex.TrimEnd(separator.ToCharArray());
return hex;
} /// <summary>
/// 打开串口
/// </summary>
private void btn_open_Click(object sender, EventArgs e)
{
if (btn_open.Text == "打开")
{
sp = new SerialPort(cbb_serials.Text, );
sp.ReceivedBytesThreshold = ;
sp.DataReceived += OnDataReceived;
//sp.WriteTimeout = 50;
//sp.ReadTimeout = 50;
sp.Open();
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
btn_send.Enabled = true;
btn_open.Text = "关闭";
}
else if (btn_open.Text == "关闭")
{
sp.Close();
sp = null;
btn_send.Enabled = false;
btn_open.Text = "打开";
}
} /// <summary>
/// 读取串口
/// </summary>
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
{
int len = sp.Read(buffer, , sp.BytesToRead);
string hex = GetHexStr(buffer, len);
// 使用ReactiveX的方式更新UI数据
scheduler.Schedule(() =>
{
lb_read.Items.Add(hex);
lb_read.SetSelected(lb_read.Items.Count - , true);
});
}
} /// <summary>
/// 发送数据
/// </summary>
private void btn_send_Click(object sender, EventArgs e)
{
string[] strs = tb_send.Text.Split(' ');
byte[] hexs = new byte[strs.Length];
for (int i = ; i < hexs.Length; i++)
{
hexs[i] = Byte.Parse(strs[i], NumberStyles.AllowHexSpecifier);
} try
{
sp.Write(hexs, , hexs.Length);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
} private void ZSerialportForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (sp != null)
sp.Close();
}
}

Winform中使用Reactivex代替BeginInvoke/Invoke来更新UI数据-LMLPHP

05-11 22:35