我爲多線程的異步套接字編寫了一個緩衝區類。我希望確保在其他操作完成之前不允許對緩衝區進行任何操作(讀取,寫入)。這個怎麼做?代碼是這樣的:如何鎖定緩衝區引用
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
}
}
如何鎖定吸氣劑?
可能重複http://stackoverflow.com/questions/505515/c-sharp-thread-safety-with -get-set) – Tarec