lock shared data using c#

Posted by menacheb on Stack Overflow See other posts from Stack Overflow or by menacheb
Published on 2010-04-27T14:05:19Z Indexed on 2010/04/27 14:13 UTC
Read the original article Hit count: 291

Filed under:
|
|

Hi,
I have a program (C#) with a list of tests to do.
Also, I have two thread. one to add task into the list, and one to read and remove from it the performed tasks.
I'm using the 'lock' function each time one of the threads want to access to the list.
Another thing I want to do is, if the list is empty, the thread who need to read from the list will sleep. and wake up when the first thread add a 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's not performed as expected (The readTread does't read from the list).
Does anyone know what is my problem, and how to make it right?
Many thanks,

© Stack Overflow or respective owner

Related posts about c#

Related posts about lock