如何锁定缓冲区引用

时间:2014-04-18 08:26:24

标签: c# multithreading

我为异步套接字写了一个缓冲类,它是多线程的。我想确保在其他操作完成(读,写)之前不允许对缓冲区执行任何操作。这该怎么做?代码如下:

 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
    }


}

如何锁定吸气剂?

1 个答案:

答案 0 :(得分:3)

我建议使用lock例如

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

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

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

}