如何锁定缓冲区引用

本文关键字:缓冲区 引用 锁定 何锁定 | 更新日期: 2023-09-27 17:58:49

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

 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
    }

}

如何锁定吸气剂?

如何锁定缓冲区引用

我建议使用lock,例如

public class A
{
  private static object lockObj = new object();
  public MyCustomClass sharedObject;
  public void Foo()
  {
    lock(lockObj)
    {
      //codes here are safe 
      //shareObject.....
    }
  }
}