Scenario: A method needs to write to the stream, another method needs to read the content of the newly written inflow, the whole process is a one-time without caching, can not use MemoryStream, that will account for the memory, and due to MemoryStream capacity is not fixed, The process of scaling up also has an impact on performance. In order to provide efficient stream read and write performance, a cache-free stream is designed.
The write and read of this stream must be divided into 2 different threads, otherwise it will not work properly, it is recommended to write using a background thread, while the read uses the current thread, that is, the stream object (read or return) that is used directly by the current thread.
The write to this stream is read-based, and if there is no read, the write waits indefinitely until there is a read action, which gets the read-side cache and writes directly to the read-side cache array.
/// <summary>///written in Reading/// </summary> Public classnocachestream:stream{PrivateManualResetEvent Enablewrite =NewManualResetEvent (false); PrivateAutoResetEvent Enableread =NewAutoResetEvent (false); Private volatile byte[] innerbuffer; Private intnum, Inneroffset, Innercount; Private BOOLIsend; Public Override BOOLCanRead {Get{return true; } } Public Override BOOLCanSeek {Get{return false; } } Public Override BOOLCanWrite {Get{return true; } } Public Override voidFlush () {Throw Newnotimplementedexception (); } Public Override LongLength {Get{Throw Newnotimplementedexception ();} } Public Override LongPosition {Get { Throw Newnotimplementedexception (); } Set { Throw Newnotimplementedexception (); } } Public Override intRead (byte[] Buffer,intOffsetintcount) { if(isend)return 0; Innerbuffer=buffer; Inneroffset=offset; Innercount=count; Num=0; Enablewrite. Set (); //Allow WriteEnableread. WaitOne ();//wait to read returnnum; } Public Override LongSeek (Longoffset, SeekOrigin origin) { Throw Newnotimplementedexception (); } Public Override voidSetLength (Longvalue) { Throw Newnotimplementedexception (); } Public Override voidWrite (byte[] Buffer,intOffsetintcount) { if(isend)return; Enablewrite. WaitOne ();//wait Read method signal while(Count >=Innercount) {array.copy (buffer, offset, innerbuffer, Inneroffset, Innercount); Offset+=Innercount; Count-=Innercount; Num+=Innercount; Enablewrite. Reset ();//Block WriteEnableread. Set ();//Allow ReadEnablewrite. WaitOne ();//wait to write } if(Count >0) {array.copy (buffer, offset, innerbuffer, Inneroffset, Count); Inneroffset+=count; Innercount-=count; Num+=count; } } /// <summary> ///End of Read-write/// </summary> Public voidEnd () {isend=true; Enableread. Set (); }}
No cache efficient stream (Nocachestream)