我想知道如何将通过串行端口接收的数据链接到在主 UI 中调用它的函数。
我希望 UI 从串口发送数据,然后挂起线程或等待直到通过串口线程接收到数据,然后再继续主 UI 线程。
有人告诉我 thread.suspend() 不是一个可以安全使用的函数,我尝试将它与 thread.resume 一起使用,但失败了。
我应该查看锁/互斥量吗?
或者 EventWaitHandles?
我彻底糊涂了!我不熟悉线程,所以任何帮助将不胜感激!谢谢。
代码如下:
public static int SerialCOM_Read(uint tRegisterAddress,out byte[] tRegisterValue,uint nBytes) {
int retVal = 1;
tRegisterValue = new byte[nBytes];
byte[] nBytesArray = new byte[4];
NBytes = nBytes;
try {
ReadFunction = true;
YetToReceiveReadData = true;
byte[] registerAddress = BitConverter.GetBytes(tRegisterAddress);
int noOfBytesForRegAdd = 1;
if (registerAddress[3] > 0) noOfBytesForRegAdd = 4;
else if (registerAddress[2] > 0) noOfBytesForRegAdd = 3;
else if (registerAddress[1] > 0) noOfBytesForRegAdd = 2;
nBytesArray = BitConverter.GetBytes(nBytes);
{
Append_Start();
Append_Operation_with_NoOfBytesForRegAdd(OPERATION.I2C_READ, noOfBytesForRegAdd);
Append_RegAdd(noOfBytesForRegAdd, tRegisterAddress);
Append_NoOfBytesOfData(nBytesArray);
Send_DataToWrite();
//Need to Suspend Thread here and Continue once the
//ReadData[i] global variable has been assigned.
for(int i=0; i<nBytes; i++)
tRegisterValue[i] = ReadData[i];
}
catch(Exception ex) {}
return retVal;
最佳答案
如果您打算阻塞 UI 线程,那么使用 DataReceived 事件就没有意义了。直接调用 SerialPort.Read/Line() 即可。这可能导致用户界面响应延迟通常是不受欢迎的,但它确实更容易上手。
关于c# - 如何将 SerialPort 接收到的数据链接到主 UI 线程的读取函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155551/