Within a C# instance method, can 'this' ever be null?

前端 未结 6 775
栀梦
栀梦 2020-12-17 08:30

I have a situation where very rarely a Queue of Objects is dequeuing a null. The only call to Enqueue is within the class itself:

m_DeltaQueue.Enqueue(this);         


        
6条回答
  •  情话喂你
    2020-12-17 08:49

    this can never be null (the CLR will raise an exception if you try to call a method on null). It's almost certainly the case that you have a synchronization bug, where two threads are trying to add to the queue simultaneously. Perhaps both threads are incrementing an index into the array and then putting their value into the same location. This means that the first thread is getting its value overwritten.

    Either synchronize your access (e.g. with lock) or use a ConcurrentQueue (in .Net 4).

提交回复
热议问题