3

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Joey.Z
  • 4,492
  • 4
  • 38
  • 63
  • possible duplicate of [C# thread safety with get/set](http://stackoverflow.com/questions/505515/c-sharp-thread-safety-with-get-set) – Tarec Apr 18 '14 at 08:30

1 Answers1

3

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.....
    }
  }

}
Reza
  • 18,865
  • 13
  • 88
  • 163
  • Will it be ok if `return` inside the lock? I am gonna try this. – Joey.Z Apr 18 '14 at 08:36
  • @zoujyjs yes it is ok – Reza Apr 18 '14 at 08:42
  • And btw, is if I have a member `private int state` that can access by multiple threads, will `private volatile int state` be enough for this situation? – Joey.Z Apr 18 '14 at 10:40
  • @zoujyjs based on arguments in this link `http://stackoverflow.com/questions/72275/when-should-the-volatile-keyword-be-used-in-c` i don't think that is a good idea, instead put every code that reefers to `state` into a `lock` block. – Reza Apr 18 '14 at 10:46