C # Ring buffer (queue) fully implemented _c# tutorial

Source: Internet
Author: User

Company projects are often designed to serial communication, TCP communications, and most are real-time large data transmission, and then we all know that protocol communication must be related to, sealing, unpacking, sticky, check ... What ghost concept a lot of, say simple is to have an efficient reusable buffer. In accordance with the Code of agricultural inertia is to Baidu, Google search to see if there are ready-made things can be used directly, but I did not find, well, it is not difficult to achieve a bai. Pull the crap out of ...

Why do we use ring queues?
The ring queue is a very useful data structure in practical programming, and it has the following characteristics:
It is a end-to-end data structure of the FIFO, using the linear space of the array, the data organization is simple. Can soon know whether the queue is full empty. can access data at a very fast rate.
Because there are simple and efficient reasons, even in the hardware has implemented a ring queue.

C # fully implemented (can be used directly)
I am a novice this code must have deficiencies, I hope you point out the exchange, involving multi-threaded synchronization issues, please the caller complete, not nonsense directly on the code.

 public class Ringbuffermanager {public byte[] Buffer {get; set;}//memory-storing array public int Datacount {get; set;}//  Write data size public int Datastart {get; set;}//Data start index public int dataend {get; set;} Data End Index public ringbuffermanager (int buffersize) {datacount = 0; Datastart = 0;
    dataend = 0;
  Buffer = new Byte[buffersize];
      Public byte This[int index] {get {if (index >= datacount) throw new Exception ("Ring buffer exception, index overflow");
      if (Datastart + Index < buffer.length) {return buffer[datastart + index];
      else {return buffer[(Datastart + index)-buffer.length];
  }} public int getdatacount ()//Get the number of bytes currently written {return datacount;
  public int Getreservecount ()//Get the remaining number of bytes {return buffer.length-datacount;
  public void Clear () {datacount = 0;
 public void Clear (int count)//empty data of the specified size {if (Count >= datacount)///If the data that needs to be cleaned is greater than the existing data size, clean all   {datacount = 0;
      Datastart = 0;
    dataend = 0; else {if (Datastart + count >= buffer.length) {Datastart = (Datastart + count)-Buffer .
      Length;
      else {Datastart = count;
    } Datacount-= count; } public void WriteBuffer (byte[] buffer, int offset, int count) {Int32 Reservecount = Buffer.length-dataco
    Unt
      if (Reservecount >= count)//free space is enough to use {if (Dataend + count < buffer.length)//Data not ending
        {array.copy (buffer, offset, buffer, dataend, count);
        Dataend + = count;
      Datacount + = count;
        else//Data end index beyond end loop to start {System.Diagnostics.Debug.WriteLine ("cache restart ...");   Int32 Overflowindexlength = (dataend + count)-buffer.length;       Exceeding index length Int32 endpushindexlength = count-overflowindexlength; Data length filled at end array.copy (buffer, offset, buffer, dataend, endingPushindexlength);
        dataend = 0;
        Offset + + endpushindexlength;
        Datacount + = Endpushindexlength;
        if (overflowindexlength!= 0) {array.copy (buffer, offset, buffer, dataend, overflowindexlength);                   } dataend + = Overflowindexlength;                  End index Datacount + = Overflowindexlength; Cache Size}} else {//cache overflow, not processing}} public void Readbuffer (byte[] Targetbytes,int32 OFFSE
    T, Int32 count) {if (Count > Datacount) throw new Exception ("Ring buffer exception, read length greater than data length");
    Int32 Tempdatastart = Datastart;
    if (Datastart + Count < buffer.length) {array.copy (Buffer, Datastart, targetbytes, offset, count);  else {Int32 Overflowindexlength = (Datastart + count)-buffer.length;       Exceeding index length Int32 endpushindexlength = count-overflowindexlength; Padding at the end of the data length array.copy (Buffer, Datastart, targetbytes, offset, endpushindExlength);
      
      Offset + + endpushindexlength;
      if (overflowindexlength!= 0) {array.copy (Buffer, 0, targetbytes, offset, overflowindexlength); }} public void WriteBuffer (byte[] buffer) {writebuffer (buffer, 0, buffer.
  Length);

 }

}

Invoke instance
Production

 int len = sconn.receive (receivebuffer, 0, Receivebuffer.length, socketflags.none, out SE);
if (len <= 0) throw new Exception ("disconnect..");
if (len > 0)
{
  lock (Lockreceivebuffer)
  {while
    (len + receivebuffermanager.datacount > Max_) Buffer_len)    //cache overflow handling
    {
      monitor.wait (lockreceivebuffer,10000);
    }
    Receivebuffermanager.writebuffer (receivebuffer, 0, Len);
    Monitor.pulseall (Lockreceivebuffer);
  }
 

Consumption

 Lock (Lockreceivebuffer)
{
  freame_byte = new Byte[framelen];
  Receivebuffermanager.readbuffer (freame_byte, 0, Framelen);
  Receivebuffermanager.clear (Framelen);
} 

Verify
The TCP large data continuous test does not have a problem memory problem for a week.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.