Sometimes you need to save the latest N records for the time needed to call, C # There is no pointer, how to do it? We use arrays and byte bytes to complete a class:
Public classBuffer<t> { Privatet[] _ts; Private byte_index =0; Private int_capcity; PublicBuffer (intcapcity) { //sets the size of the array to 2 of the n-th square while(Capcity & Capcity-1) !=0) capcity++; _ts=NewT[capcity]; _capcity=capcity; } Public voidWrite (T t) {_ts[_index% _capcity] =T; _index++; } PublicIenumerable<t>Read () {byteindex =_index; for(inti =0; I < _ts. Count (); i++) {Index--; yield return_ts[index%_capcity]; } } }
Explain:
1.byte _index=0;
_index--; =0xff
_index++;//=0
The use of this feature of Byte, write the time + +, read time--without regard to the boundary, is not more convenient.
2. Why is the size of the array automatically adjusted to the n-th square of 2?
That is because only 2 of the nth Time, (0xFF _capcity) ==_capcity-1, to achieve the traversal of the array.
To test, call the following code:
Static voidMain (string[] args) {Buffer<int> buffer =Newbuffer<int> (Ten); varTaskwrite = Task.Factory.StartNew (() = { for(inti =0; I < -; i++) {buffer. Write (i); Console.WriteLine ($"Write:i={i}"); Task.delay ( -). Wait (); } }); varTaskread = Task.Factory.StartNew (() = { for(inti =0; I <7; i++) {Console.WriteLine ("Read:"+string. Join (",", buffer. Read ())); Task.delay ( +). Wait (); } }); Task.waitall (Taskwrite, Taskread); } }
Results:
Suitable for:
1. Small cache, <=255
Of course you can >255, as long as the type of _index to Uint16,uint32 or UInt64, the size is 0xffff,0xffffffff and 0xFFFFFFFFFFFFFFFF, but so much useful? Is it called cache?
2. Single-thread read single-threaded write operation
C # fixed-size cache