ThreadPool.QueueUserWorkItem
The documentation of the method above says the following about its return type:
true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.
Does that mean that the function never returns false? But throws instead? If so, then why have a return type at all? I would say, or return true/false whether the WorkItem has been queued, or be of type void and throw when the WorkItem couldn't be queued.
I know there is this duplicate question, but it really isn't much of definite answer in my opinion.
You need to read the docs carefully. While MSDN states:
true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.
...just bellow also states:
NotSupportedException: The common language runtime (CLR) is hosted, and the host does not support this action.
I mean, NotSupportedException will be thrown if the hosting environment doesn't support thread pooling.
Thus, if you're queueing threads where you can do so, you don't need a try/catch block. At least, you can check that the thread could be queued using the regular boolean return value.
Does that mean that the function never returns false? But throws instead? If so, then why have a return type at all
Lets look at the source code:
//ThreadPool has per-appdomain managed queue of work-items. The VM is
//responsible for just scheduling threads into appdomains. After that
//work-items are dispatched from the managed queue.
[System.Security.SecurityCritical] // auto-generated
private static bool QueueUserWorkItemHelper(
WaitCallback callBack, Object state, ref StackCrawlMark stackMark, bool compressStack)
{
bool success = true;
if (callBack != null)
{
//The thread pool maintains a per-appdomain managed work queue.
//New thread pool entries are added in the managed queue.
//The VM is responsible for the actual growing/shrinking of
//threads.
EnsureVMInitialized();
// If we are able to create the workitem,
// we need to get it in the queue without being interrupted
// by a ThreadAbortException.
//
try { }
finally
{
QueueUserWorkItemCallback tpcallBack = new QueueUserWorkItemCallback(
callBack, state, compressStack, ref stackMark);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, true);
success = true;
}
}
else
{
throw new ArgumentNullException("WaitCallback");
}
return success;
}
It seems that success will truly either return true, as it is initially set before queuing the item, or throw an exception in case the runtime is unable to queue the delegate.
Any better ideas?
That seems redundant to me, unless you don't really trust the run-time environment and not sure if it supplies an underlying thread-pooling mechanism. Otherwise if you're using Microsoft's run-time, you should be good simply using the original QueueUserWorkItem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With