A null object that is not null

I am using 2 threads to act as producer / consumer using a double queue ( http://www.codeproject.com/KB/threads/DoubleQueue.aspx ). Sometimes in my second thread, I get an object that is NULL, but that shouldn't be the way I filled it in in the first thread.

I've tried this:

if(myObject.Data == null)
{
  Console.WriteLine("Null Object") // <-- Breakpoint here
}

      

When I find my breakpoint, I can look at myObject.Data and it is indeed NULL, but when I press F10 and go to the next line (which is }

) myObject.Data is not NULL. I also added myObject lock before

if....

to make sure no one is using this object.

How is this possible and what can I do?

+2


a source to share


3 answers


Locking on myObject means that you are locking the object referenced by myObject. If another thread changes the value of myObject, it is a new object that no one is blocking.

For locks, I advise you to declare a specific object that you only use for locking, for example:



private static readonly object MyLock = new object();

      

+8


a source


Announces

public static object LockObject = new object();

      

in the producer thread, do something like this:

lock(LockObject)
{
myObject.Data = ....
}

      



and in the consumer thread, do something like this:

lock(LockObject)
{
    if(myObject.Data == null)
    {
       Console.WriteLine("Null Object") // <-- Breakpoint here
    }
    else
    {
    // Do something
    }   
}

      

This should help you.

+2


a source


Use static object for blocking

0


a source







All Articles