2013-10-16 56 views
1

我繼承了一些循環來自BinaryReader的響應的代碼,並且它工作正常(返回2個字節)一段時間,但客戶端需要一段時間來響應(我假設)並且代碼落入catch邏輯。BinaryReader ReadByte()有沒有超時?

我找不到任何有關ReadByte()等待多久的文檔,它似乎等待大約3秒鐘,然後失敗。

有誰知道到底ReadByte是如何工作的?我可以配置它以某種方式等待一段時間?我的代碼如下,謝謝。

public virtual Byte[] Send(Byte[] buffer, Int32 recSize) { 
    Byte[] rbuffer = new Byte[recSize]; 

    var binaryWriter = new BinaryWriter(stream); 
    var binaryReader = new BinaryReader(stream); 

    Int32 index = 0; 
    try { 
     binaryWriter.Write(buffer); 

     do { 
      rbuffer[index] = binaryReader.ReadByte(); // Read 1 byte from the stream 
      index++; 
     } while (index < recSize); 

    } catch (Exception ex) { 
     Log.Error(ex); 
     return rbuffer; 
    } 
    return rbuffer; 
} 

PS - recSize在代碼中是2,它總是希望返回2個字節。

+0

您可以包含此方法的函數定義以及發生失敗時引發的異常的詳細信息。 –

+0

當然@ScottChamberlain,我剛剛更新了它 –

回答

1

BinaryReader本身沒有超時,它只是基礎流的包裝。即將超時的事物是您通過的任何流,如stream。您必須修改該對象的超時值(或者,如果該流只是另一個包裝器,則爲父項)。

你根本不需要使用BinaryReader來做你想做的事情,假設bufferbyte[]你也不需要BinaryWriter。

Byte[] rbuffer = new Byte[recSize]; 

try { 
    stream.Write(buffer, 0, buffer.Length); 

    Int32 index = 0; 
    do 
    { 
     index += stream.Read(rbuffer, index, rbuffer.Length - index); 
    } while (index < recSize); 

} catch (Exception ex) { 
    Log.Error(ex); 
    return rbuffer; //I would either let the exception bubble up or return null here, that way you can tell the diffrence between a exception and an array full of 0's being read. 
} 
+0

啊,好的斯科特,我看了看代碼,它似乎是一個全局變量。它的定義是:受保護的內部System.IO.Stream stream = null; –

+0

@MarkKadlec在代碼後面會有一個'stream = new Somthing(...)'這是它被設置的地方。看到你的更新,它看起來像是某種'NetworkStream',你需要找到它的創建位置並改變超時時間。 –

+0

謝謝Scott,就是這樣。可悲的是,這並沒有解決我的問題(我認爲它在客戶端),但現在我可以輕鬆地切換readTimeout。 –