[英]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 ). 我使用双线程( http://www.codeproject.com/KB/threads/DoubleQueue.aspx )使用2个线程来充当产品/消费者。 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. 有时在我的第二个线程中,我得到一个NULL的对象,但它不应该像我在第一个线程中填充它一样。
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. 当我的断点点击时,我可以看到myObject.Data,实际上它是NULL,但是当我点击F10然后转到下一行(这是}
)myObject.Data 不是 NULL。 I also added a lock on myObject before 我之前也在myObject上添加了一个锁
if .... 如果....
to be sure that no one whould use this object. 确保没有人会使用这个物体。
How is that possible and what can I do ? 怎么可能,我该怎么办?
Locking on myObject means you're locking on the object myObject refers to. 锁定myObject意味着你要锁定myObject引用的对象。 If another thread changes the value of myObject, it's a new object that no one is locking on. 如果另一个线程更改了myObject的值,则它是一个没有人锁定的新对象。
For locks, I advise you declare specific object you only use for locking, for instance: 对于锁,我建议您声明仅用于锁定的特定对象,例如:
private static readonly object MyLock = new object();
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. 这应该可以帮到你。
使用静态对象进行锁定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.