我需要使用try-catch还是检查ThreadPool.QueueUserWorkItem的返回值

本文关键字:ThreadPool 检查 QueueUserWorkItem 返回值 try-catch | 更新日期: 2023-09-27 18:26:35

ThreadPool.QueueUserWorkItem

上面方法的文档说明了以下关于其返回类型的信息:

如果该方法已成功排队,则为true;如果工作项无法排队,则引发NotSupportedException。

这是否意味着函数永远不会返回false?但是投掷呢?如果是,那么为什么要有一个返回类型呢?无论WorkItem是否已排队,我都会说,或返回true/false,或者当WorkItem无法排队时,返回void和throw类型。

我知道这是一个重复的问题,但在我看来,这并不是一个确切的答案。

我需要使用try-catch还是检查ThreadPool.QueueUserWorkItem的返回值

您需要仔细阅读文档。MSDN声明:

如果该方法已成功排队,则为true;NotSupportedException为如果工作项无法排队,则引发。

下面还说:

NotSupportedException:托管公共语言运行库(CLR),并且主机不支持此操作。

我的意思是,如果托管环境不支持线程池,NotSupportedException将被抛出。

因此,如果您在可以这样做的处对线程进行排队,则不需要try/catch块。至少,您可以使用常规布尔返回值检查线程是否可以排队。

这是否意味着函数永远不会返回false?但是投掷相反如果是,那么为什么所有都有返回类型

让我们看看源代码:

//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;
}

成功似乎真的会返回true,因为它是在对项目进行排队之前初始设置的,或者在运行时无法对委托进行排队时抛出异常。

有更好的主意吗?

这对我来说似乎是多余的,除非你真的不信任运行时环境,也不确定它是否提供了底层的线程池机制。否则,如果您使用的是Microsoft的运行时,那么只需使用原始的QueueUserWorkItem就可以了。