【发布时间】:2011-08-23 02:01:39
【问题描述】:
我想知道如何将通过串行端口接收到的数据链接到在主 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;
}
【问题讨论】:
-
您的代码甚至无法编译,您的 catch 块在 inside 您的 try 块中,这是无效的语法。
-
您是在编写 WPF 还是 WinForms UI?在任何一种情况下,出于任何原因暂停 UI 线程似乎都是一个坏主意。听起来您正试图在应用程序上强制执行“半双工”通信模式,串行端口客户端应用程序通常不需要这种模式。这是link,无论如何可能会有所帮助。
-
对不起,它是无效的语法,我错误地剪切和粘贴了我的代码,错过了一个}。我正在使用 Windows 窗体 GUI,感谢您的链接! :)
-
这看起来已回答,请关闭您的问题。帮助您解决问题的帖子旁边的大复选标记。
标签: c# thread-safety serial-port