c# - Implementing reading when there are asynchronous writes -


i have stream can read , write @ same time. msdn documentation says should return 0 read(buffer, offset, count) method when end of stream reached.

as reading , writing asynchronous reading needs wait until write happens if internal buffer empty.

i'm struggling how writing method can signal has been written. best can think of dispose() (or close()) method signal end of writing feels wrong.

my stream class implemented as:

public class continuousstream : stream {     private readonly iproducerconsumercollection<byte> _buffer;      public continuousstream() => _buffer = new concurrentqueue<byte>();      public override int read(byte[] buffer, int offset, int count)     {         var maxbytecount = offset + count > buffer.length ? buffer.length : count;         var actualbytesread = 0;          (var = offset; < maxbytecount && _buffer.trytake(out var b); i++)         {             buffer[i] = b;             actualbytesread++;         }          return actualbytesread;     }      public override void write(byte[] buffer, int offset, int count)     {         var maxbytecount = offset + count > buffer.length ? buffer.length : count;         (var = offset; < maxbytecount; i++)         {             _buffer.tryadd(buffer[i]);         }     } } 

to clarify

reading , writing happen simultaneously. reading shouldn't have wait until buffered before running. how can signal stream writing happen has happened?

actually, don't quite understand why need stream , can't use iproducerconsumercollection alone. many of parameters meaningless. use trytake & tryadd instead of read & write in first place.

but can use autoresetevent this:

public class continuousstream : stream {     private readonly autoresetevent _are = new autoresetevent(false);     private readonly iproducerconsumercollection<byte> _buffer = new concurrentqueue<byte>();      public override int read(byte[] buffer, int offset, int count)     {         _are.waitone();         var maxbytecount = offset + count > buffer.length ? buffer.length : count;         var actualbytesread = 0;          (var = offset; < maxbytecount && _buffer.trytake(out var b); i++)         {             buffer[i] = b;             actualbytesread++;         }          return actualbytesread;     }      public override void write(byte[] buffer, int offset, int count)     {         var maxbytecount = offset + count > buffer.length ? buffer.length : count;         (var = offset; < maxbytecount; i++)         {             _buffer.tryadd(buffer[i]);             _are.set();         }     } } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -