Share via


ThreadPool.QueueUserWorkItem returns false on failure!

ThreadPool.QueueUserWorkItem is commonly used to execute some task in the background at a later point in time using a thread from the thread pool. If you read the MSDN documentation carefully, you'll note it says:

Return Value

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

Exception type Condition

ApplicationException

An out-of-memory condition was encountered.

Wow! It might just return false if it fails instead of throwing an exception. This must be one of those early APIs that they didn't get right the first time and couldn't change later for legacy reasons. It also uses ApplicationException, which seems very odd. I rarely see code that checks the result, including the sample code on the MSDN documentation site! This could cause unexpected failures in your application.

Comments

  • Anonymous
    March 15, 2006
    You should probably have a talk with Brad Abrams.

    Exceptions and errors are different.  Exception is not a mechanism to throw errors.  A function can throw an exception if it thinks continuing from that state would fail the program.

    If QueueWorkItem fails, he should just return an error.  If QueueWorkItem ends up in a state that the program can no longer continue, then by all means throw an exception.

    Then what is the purpose of the exception handling? It should just save some state, give a meaningful error message and exit.

    Regarding your comment on not checking return code, I am sorry to say, a person writing such code should move to marketing department.

    Summary:  Exceptions are irrecoverable errors, that's it.

  • Anonymous
    March 15, 2006
    Exceptions are an error handling mechanism. FailFast is the mechanism for irrecoverable errors. If you can't continue excecution, you should FailFast, not throw an exception.

    A function should throw an exception if it doesn't do what it says it's going to do. So, if it doesn't queue a work item, it should throw an exception. If it was called TryQueueWorkItem, it would be expected to return a bool with the success state.

    You should take a look at http://msdn2.microsoft.com/en-us/library/ms229014.aspx and http://msdn2.microsoft.com/en-us/library/ms229030(VS.80).aspx. These are from Brad's book.

  • Anonymous
    March 31, 2006
    The comment has been removed

  • Anonymous
    July 26, 2006
    In part 2, I showed a base class for DataModels. In this post, I will describe a sample implementation....

  • Anonymous
    January 06, 2007
    In part 2 , I showed a base class for DataModels. In this post, I will describe a sample implementation.

  • Anonymous
    May 29, 2009
    PingBack from http://paidsurveyshub.info/story.php?title=dan-crevier-s-blog-threadpool-queueuserworkitem-returns-false-on-failure