Created
May 7, 2020 11:59
-
-
Save BanksySan/3ab076bd363b605a399268948b66bfa0 to your computer and use it in GitHub Desktop.
Blog: Writing a Concurrent .NET Stream (6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public bool WritingFinished { get; private set; } | |
public void CloseWrite() | |
{ | |
WritingFinished = true; | |
_readWait.Set(); | |
} | |
public override int Read(byte[] buffer, int offset, int count) | |
{ | |
var maxByteCount = offset + count > buffer.Length ? buffer.Length : count; | |
if (_buffer.Count == 0) | |
{ | |
_readWait.WaitOne(); | |
} | |
_readWait.Reset(); | |
var actualBytesRead = 0; | |
for (var i = offset; i < maxByteCount && _buffer.TryTake(out var b); i++) | |
{ | |
buffer[i] = b; | |
actualBytesRead++; | |
} | |
return actualBytesRead; | |
} | |
public override void Write(byte[] buffer, int offset, int count) | |
{ | |
if (WritingFinished) | |
{ | |
throw new InvalidOperationException("Attempt to write after CloseWrite() has been called."); | |
} | |
var maxByteCount = offset + count > buffer.Length ? buffer.Length : count; | |
for (var i = offset; i < maxByteCount; i++) | |
{ | |
_buffer.TryAdd(buffer[i]); | |
} | |
_readWait.Set(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment