簡體   English   中英

SerialPort.Read(byte [],int32,int32)沒有阻塞但我想要它 - 我該如何實現?

[英]SerialPort.Read(byte[], int32, int32) is not blocking but i want it to - how do I achieve?

我正在編寫一個與一台測試設備交談的界面。 設備通過串行端口進行通信,並以發送的每個命令以已知的字節數進行響應。

我目前的結構是:

  • 發送命令
  • 讀回指定字節數
  • 繼續申請

但是,當我使用SerialPort.Read(byte [],int32,int32)時,該函數沒有阻塞。 所以,例如,如果我調用MySerialPort.Read(byteBuffer, 0, bytesExpected); ,函數返回小於指定的bytesExpected 這是我的代碼:

public bool ReadData(byte[] responseBytes, int bytesExpected, int timeOut)
{
    MySerialPort.ReadTimeout = timeOut;
    int bytesRead = MySerialPort.Read(responseBytes, 0, bytesExpected);
    return bytesRead == bytesExpected;
}

我將此方法稱為:

byte[] responseBytes = new byte[13];
if (Connection.ReadData(responseBytes, 13, 5000))
    ProduceError();

我的問題是,我似乎無法像我所說的那樣讀取完整的13個字節。 如果我在我的SerialPort.Read(...)之前放置一個Thread.Sleep(1000) SerialPort.Read(...)一切正常。

如何超出timeOut或讀取指定的字節數,如何強制Read方法阻塞?

這是預期的; 大多數IO API允許您指定上限 - 它們只需返回至少一個字節,除非它是EOF,在這種情況下它們可以返回非正值。 要補償,你循環:

public bool ReadData(byte[] responseBytes, int bytesExpected, int timeOut)
{
    MySerialPort.ReadTimeout = timeOut;
    int offset = 0, bytesRead;
    while(bytesExpected > 0 &&
      (bytesRead = MySerialPort.Read(responseBytes, offset, bytesExpected)) > 0)
    {
        offset += bytesRead;
        bytesExpected -= bytesRead;
    }
    return bytesExpected == 0;
}

唯一的問題是您可能需要通過使用Stopwatch或類似方法來減少每次迭代的超時,以查看已經過了多少時間。

請注意,我還刪除了responseBytes上的ref - 您不需要它(您不重新分配該值)。

嘗試將超時更改為InfiniteTimeout

如果在SerialPort.ReadTimeout之前沒有可用的字節,則SerialPort.Read應該拋出TimeoutException。 因此,此方法准確讀取所需的數字或字節,或引發異常:

    public byte[] ReadBytes(int byteCount) {
        try
        {
            int totBytesRead = 0;
            byte[] rxBytes = new byte[byteCount];
            while (totBytesRead < byteCount) {
                int bytesRead = comPort.Read(rxBytes, totBytesRead, byteCount - totBytesRead);
                totBytesRead += bytesRead;
            }



            return rxBytes;
        }
        catch (Exception ex){

            throw new MySerialComPortException("SerialComPort.ReadBytes error", ex);            
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM