gpt4 book ai didi

c# - 如何锁定缓冲区引用

转载 作者:行者123 更新时间:2023-11-30 16:12:20 26 4
gpt4 key购买 nike

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

 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
}


}

如何锁定 setter/getter ?

最佳答案

例如,我建议使用lock

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

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

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

}

关于c# - 如何锁定缓冲区引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23150325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com