在C#中,可以使用多種方法實現緩沖區的并發控制。下面列舉了幾種常用的方法:
private object locker = new object();
private List<int> buffer = new List<int>();
public void AddToBuffer(int value)
{
lock (locker)
{
buffer.Add(value);
}
}
public int GetFromBuffer()
{
lock (locker)
{
if (buffer.Count > 0)
{
int value = buffer[0];
buffer.RemoveAt(0);
return value;
}
else
{
return -1;
}
}
}
private ConcurrentQueue<int> buffer = new ConcurrentQueue<int>();
public void AddToBuffer(int value)
{
buffer.Enqueue(value);
}
public int GetFromBuffer()
{
int value;
if (buffer.TryDequeue(out value))
{
return value;
}
else
{
return -1;
}
}
private SemaphoreSlim semaphore = new SemaphoreSlim(1);
private List<int> buffer = new List<int>();
public void AddToBuffer(int value)
{
semaphore.Wait();
buffer.Add(value);
semaphore.Release();
}
public int GetFromBuffer()
{
semaphore.Wait();
if (buffer.Count > 0)
{
int value = buffer[0];
buffer.RemoveAt(0);
semaphore.Release();
return value;
}
else
{
semaphore.Release();
return -1;
}
}
以上是幾種在C#中實現緩沖區并發控制的方法,具體選擇哪種方法取決于具體的應用場景和需求。