我正在创建一个通过 FT2232H USB/RS232 转换器与设备通信的应用程序。对于通信,我使用 FTDI 网站上的 FTD2XX_NET.dll 库。
我正在使用两个线程:
当我在接收器线程运行时尝试将任何数据写入设备时遇到问题。主线程只是挂断了 ftdiDevice.Write 函数。
我试图同步两个线程,以便只有一个线程可以同时使用读/写功能,但它没有帮助。
下面的代码负责通信。请注意,以下函数是 FtdiPort 类的方法。
收件人的线程
private void receiverLoop()
{
if (this.DataReceivedHandler == null)
{
throw new BackendException("dataReceived delegate is not set");
}
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
byte[] readBytes = new byte[this.ReadBufferSize];
while (true)
{
lock (FtdiPort.threadLocker)
{
UInt32 numBytesRead = 0;
ftStatus = ftdiDevice.Read(readBytes, this.ReadBufferSize, ref numBytesRead);
if (ftStatus == FTDI.FT_STATUS.FT_OK)
{
this.DataReceivedHandler(readBytes, numBytesRead);
}
else
{
Trace.WriteLine(String.Format("Couldn't read data from ftdi: status {0}", ftStatus));
Thread.Sleep(10);
}
}
Thread.Sleep(this.RXThreadDelay);
}
}
编写从主线程调用的函数
public void Write(byte[] data, int length)
{
if (this.IsOpened)
{
uint i = 0;
lock (FtdiPort.threadLocker)
{
this.ftdiDevice.Write(data, length, ref i);
}
Thread.Sleep(1);
if (i != (int)length)
{
throw new BackendException("Couldnt send all data");
}
}
else
{
throw new BackendException("Port is closed");
}
}
用于同步两个线程的对象
static Object threadLocker = new Object();
启动接收者线程的方法
private void startReceiver()
{
if (this.DataReceivedHandler == null)
{
return;
}
if (this.IsOpened == false)
{
throw new BackendException("Trying to start listening for raw data while disconnected");
}
this.receiverThread = new Thread(this.receiverLoop);
//this.receiverThread.Name = "protocolListener";
this.receiverThread.IsBackground = true;
this.receiverThread.Start();
}
如果我评论以下行,ftdiDevice.Write 函数不会挂断:
ftStatus = ftdiDevice.Read(readBytes, this.ReadBufferSize, ref numBytesRead);