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)
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,
multithreading c # locking
menacheb
source share