Block shared data with C #

I have a program (C #) with a list of tests.
In addition, I have two threads. one for adding tasks to the list, and another for reading and deleting completed tasks from it.
I use the lock function every time one of the threads wants to access the list.
Another thing I want to do is if the list is empty, the thread that should read from the list will sleep. and wake up when the first thread adds the task to the list. Here is the code I wrote:

... List<String> myList = new List(); Thread writeThread, readThread; writeThread = new Thread(write); writeThread.Start(); readThraed = new Thread(read); readThread.Start(); ... private void write() { while(...) { ... lock(myList) { myList.Add(...); } ... if (!readThread.IsAlive) { readThraed = new Thread(read); readThread.Start(); } ... } ... } private void read() { bool noMoreTasks = false; while (!noMoreTasks) { lock (MyList)//syncronize with the ADD func. { if (dataFromClientList.Count > 0) { String task = myList.First(); myList.Remove(task); } else { noMoreTasks = true; } } ... } readThread.Abort(); } 

Apparently, I did it wrong and it did not execute as expected (readTread is not read from the list).
Does anyone know what my problem is and how to do it right?
Many thanks,

+6
multithreading c # locking
source share
2 answers

You need a blocking queue. This is like a normal queue, except for Dequeue method blocks if nothing is queued. Here is one implementation. After you implement the blocking queue, everything else is easy. Just be careful which blocking queue implementation you are using. I have seen many examples that have subtle threading issues. It’s best to stick with the link I provided.

 public class Example { private BlockingQueue<Task> m_Queue = new BlockingQueue<Task>(); public void StartExample() { Thread producer = new Thread(() => Producer()); Thread consumer = new Thread(() => Consumer()); producer.Start(); consumer.Start(); producer.Join(); consumer.Join(); } private void Producer() { for (int i = 0; i < 10; i++) { m_Queue.Enqueue(new Task()); } } private void Consumer() { while (true) { Task task = m_Queue.Dequeue(); } } } 
+3
source share

I would advise you to take a look at Jon Skeet Sample manufacturer . For more information on Consumer Producer, check out Wikipedia.

+2
source share

All Articles