Oddur Magnusson

Object reference not set to an instance of a human being

ThreadPool.QueueUserWorkItem Traps


The  QueueUserWorkItem is a function I've used a lot to queue up things that should execute async calls. And I've always called it like so:

  ThreadPool.QueueUserWorkItem ( DoIt, someStateVariable) ;

And things have been fine and dandy. Of course I thought that the QueueUserWorkItem method would return void since it's an Async call. Well Actually it's not async since it does some work queuing up the call, which could fail, and of course if it fail it should throw a Exception.
But it turns out that is not the case. Using the only real bcl documentation, it turns out it calls out to a extern method that returns a bool, and returns that bool as a result Code if whether the queuing was successful or not! And the MSDN documentation confirms this:

Return Value
true if the method is successfully queued; otherwise, false.

So each time I have been queuing stuff up, I've been blindly assuming that the queuing was successful. Rather I should have been either checking the result and re-queue, or throw a custom exception if it returns false.

Why the method does not throw a exception when it fails, like everything else, is a mystery to me.

Anybody know why ?

Posted: Jan 02 2007, 10:24 AM by oddurmag | with 1 comment(s)
Filed under: , , ,

Comments

Eric said:

That's pretty what I was expecting myself. I was starting new threads on a per request basis, and happily learned the error of my ways before it put pressure on a production system.

I know that the real way to do this would be to check the status of the thread, but curiously, would the application on error event get thrown if an async thread were to fail?

# January 16, 2007 12:59 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)