Joey.Z
Joey.Z

Reputation: 4770

How to lock a buffer reference

I write a buffer class for asynchronous socket which is multi-threading. And I want to ensure that any operation on the buffer is not allowed until other operation is finished (read, write). How to do this? The code is like:

 public class ByteBuffer {
    private static ManualResetEvent mutex =
        new ManualResetEvent(false);
    byte[] buff;
    int capacity;
    int size;
    int startIdx;

    public byte[] Buffer {
        get { return buff; }
    }
    public int StartIndex {
        get { return startIdx; }
    }
    public int Capacity {
        get { return capacity; }
    }

    public int Length {
        get { return size; }
    }

    // Ctor
    public ByteBuffer() {
        capacity = 1024;
        buff = new byte[capacity];
        size = startIdx = 0;
    }
    // Read data from buff without deleting
    public byte[] Peek(int s){
        // read s bytes data
    }
    // Read data and delete it
    public byte[] Read(int s) {
        // read s bytes data & delete it
    }

    public void Append(byte[] data) {
        // Add data to buff
    }

    private void Resize() {
        // resize the buff
    }


}

And how to lock the getter?

Upvotes: 3

Views: 582

Answers (1)

Reza
Reza

Reputation: 19863

I suggest using lock for example

public class A
{
  private static object lockObj = new object();

  public MyCustomClass sharedObject;
  public void Foo()
  {
    lock(lockObj)
    {

      //codes here are safe 
      //shareObject.....
    }
  }

}

Upvotes: 3

Related Questions