我为异步套接字写了一个缓冲类,它是多线程的。我想确保在其他操作完成(读,写)之前不允许对缓冲区执行任何操作。这该怎么做?代码如下:
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
}
}
如何锁定吸气剂?
答案 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.....
}
}
}