Skip to main content
edited title
Link
brunnerh
  • 188k
  • 30
  • 362
  • 434

c#: how How to use a mutex

Source Link
Pedro
  • 4.2k
  • 10
  • 64
  • 99

c#: how to use a mutex

I have one thread, that is sending data stored in a buffer of type List< string> via tcp. Another thread is writing into the buffer. As I am not very familiar with c# I'd like to know how I should use lock or Mutex correctly.

This is the code I'd like to use eventually:

 while(buffer.isLocked()) { buffer.wait(); } buffer.lockBuffer(); buffer.add(tcpPacket); buffer.unlockBuffer(); buffer.notify(); 

This is my current code. I hope someone can help me complete it.

public class Buffer { private Mutex mutex; private List<string> buffer; private bool locked = false; public Buffer() { mutex = new Mutex(false); buffer = new List<string>(); } public bool isLocked() { return locked; } public void lockBuffer() { if (!locked) { //... locked = true; } } public void unlockBuffer() { if(locked) { mutex.ReleaseMutex(); locked = false; } } public void wait() { mutex.WaitOne(); } public void notify() { //... } }