Re: Queue.Dequeue() causes exception "Object reference not set to an instance of an object."
- From: Peter Duniho <no.peted.spam@xxxxxxxxxxxxxxxxxx>
- Date: Sat, 21 Nov 2009 02:02:30 -0800
newbie18 wrote:
Hi All,
I'm using almost the same approach as alexia in using Queue. However,
I'm not using any synchronize queue.
The sample code as follow has been running for about a year, but
recently I encounter "Object reference not set to an instance of an
object" error. Wondering would it be cause by the Queue. This error is
occurred at Process function in cSocket class. Please advise. [...]
I'm amazed the code worked at all.
The first thing it ought to do is throw an InvalidOperationException, due to trying to dequeue an element from an empty queue. Specifically: there is a very high likelihood of the receiving thread not getting a chance to execute, adding something to the queue, before the original thread gets into the cSocket.Process() method and tries to dequeue an item. And that's not even counting the likelihood of the receiving thread having to wait a bit for the first data to show up in the socket.
In other words, given the code shown, it should be quite common for the Process() method to attempt to dequeue data from the queue before the other thread has ever had a chance to enqueue any data. (And _that's_ not counting the lack of any synchronization/signaling, meaning that if the receiving thread _ever_ falls behind the original thread processing data, you should get an InvalidOperationException).
But even ignoring that issue, yes...you have no synchronization at all in your code, and so your use of the queue is just as unsynchronized as that found in alexia's code, and so can have the same problems, including dequeuing a null reference.
Due to the lack of synchronization, you also have other potential threading issues. For example, you have a class member, "socClient" that is not protected by any synchronization, but which is not initialized until the Listen() method starts to execute (and even there, not right away). You also have an endless loop in your receive thread, because you don't exit the loop when Receive() returns 0 (though, maybe you get an exception, I don't recall off the top of my head...not the best way to get out, but I suppose it's better than the thread hanging).
Basically, you've got multi-threaded code that hasn't got any proper synchronization or thread-safety at all.
And on top of all that, you're asking about VB.NET code in a C# newsgroup. :p
Pete
.
- Follow-Ups:
- References:
- Prev by Date: Re: Creating a self deleting executable using .NET
- Next by Date: Re: Creating a self deleting executable using .NET
- Previous by thread: Re: Queue.Dequeue() causes exception "Object reference not set to an instance of an object."
- Next by thread: Re: Queue.Dequeue() causes exception "Object reference not set to an instance of an object."
- Index(es):
Relevant Pages
|