public Read ( byte buffer, int offset, int count ) : int | ||
buffer | byte | An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. |
offset | int | The zero-based byte offset in buffer at which to begin storing the data read from the current stream. |
count | int | The maximum number of bytes to be read from the current stream. |
return | int |
public override int Read(byte[] buffer, int offset, int count)
{
if (offset != 0)
throw new NotSupportedException("Offsets with value of non-zero are not supported");
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset + count > buffer.Length)
throw new ArgumentException("The sum of offset and count is greater than the buffer length.");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException("offset", "offset or count is negative.");
if (BlockLastReadBuffer && count >= _maxBufferLength)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "count({0}) > mMaxBufferLength({1})", count, _maxBufferLength));
if (_isDisposed)
throw CreateObjectDisposedException();
if (count == 0)
return 0;
var readLength = 0;
lock (_buffer)
{
while (!_isDisposed && !ReadAvailable(count))
{
Monitor.Wait(_buffer);
}
// return zero when the read is interrupted by a close/dispose of the stream
if (_isDisposed)
{
return 0;
}
// fill the read buffer
for (; readLength < count && _buffer.Count > 0; readLength++)
{
buffer[readLength] = _buffer.Dequeue();
}
Monitor.Pulse(_buffer);
}
return readLength;
}
public void Read() { const int sleepTime = 100; var target = new PipeStream(); target.WriteByte(0x0a); target.WriteByte(0x0d); target.WriteByte(0x09); var readBuffer = new byte[2]; var bytesRead = target.Read(readBuffer, 0, readBuffer.Length); Assert.AreEqual(2, bytesRead); Assert.AreEqual(0x0a, readBuffer[0]); Assert.AreEqual(0x0d, readBuffer[1]); var writeToStreamThread = new Thread( () => { Thread.Sleep(sleepTime); var writeBuffer = new byte[] {0x05, 0x03}; target.Write(writeBuffer, 0, writeBuffer.Length); }); writeToStreamThread.Start(); readBuffer = new byte[2]; bytesRead = target.Read(readBuffer, 0, readBuffer.Length); Assert.AreEqual(2, bytesRead); Assert.AreEqual(0x09, readBuffer[0]); Assert.AreEqual(0x05, readBuffer[1]); }