Guillaume
Guillaume

Reputation: 777

Null object that is not null

I use 2 threads to act like a produce/consumer using double queue (http://www.codeproject.com/KB/threads/DoubleQueue.aspx). Sometimes in my 2nd thread, I get an object that is NULL but it should not be as I filled it in the first thread.

I tried this:

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

When I my break point hits, I can watch myObject.Data and indeed it's NULL, but when I hit F10 and then go to the next line (which is } ) myObject.Data is not NULL. I also added a lock on myObject before

if ....

to be sure that no one whould use this object.

How is that possible and what can I do ?

Upvotes: 2

Views: 1679

Answers (3)

Pavel
Pavel

Reputation: 1

Use static object for lock

Upvotes: 0

Draško
Draško

Reputation: 2221

Declare

public static object LockObject = new object();

in producer thread do something like this:

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

and in 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 out.

Upvotes: 2

C.Evenhuis
C.Evenhuis

Reputation: 26436

Locking on myObject means you're locking on the object myObject refers to. If another thread changes the value of myObject, it's a new object that no one is locking on.

For locks, I advise you declare specific object you only use for locking, for instance:

private static readonly object MyLock = new object();

Upvotes: 8

Related Questions