110,537
社区成员
发帖
与我相关
我的任务
分享
不要让绘制UI阻塞住你的事件处理函数。正确的做法是收到数据后将相应的东西交由UI线程去做,而不是阻塞在工作线程
using System.Collections.Concurrent;
BlockingCollection<byte[]> ProcessInputQueue = new BlockingCollection<byte[]>();
static object serialPortLock = new object();
bool isAllowInput = false;
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (isAllowInput)
{
lock (serialPortLock)
{
int byteCount = serialPort.BytesToRead;
byte[] receiveBytes = new byte[byteCount];
serialPort.Read(receiveBytes, 0, byteCount);
ProcessInputQueue.Add(receiveBytes);
}
}
else
{
serialPort.DiscardInBuffer();
}
}
void StartProcessInputLoop()
{
ThreadPool.QueueUserWorkItem(obj =>
{
while (true)
{
foreach (byte[] bytes in ProcessInputQueue.GetConsumingEnumerable())
{
string info = Encoding.UTF8.GetString(bytes);
}
}
});
}
没用好多线程编程,采集所在的线程和datagridview所在的UI线程需要异步。
看看你的代码
或者是你接收数据的代码要优化
在文本文件接收看下效果
serialport 波特率设置正确了不