【问题标题】:What is this unusual code in ThreadPool?ThreadPool 中这个不寻常的代码是什么?
【发布时间】:2017-04-12 16:45:40
【问题描述】:

当它显示以下内容时,我正在使用 Reflector 仔细阅读 .Net ThreadPool 的一些源代码:

private static bool QueueUserWorkItemHelper(WaitCallback callBack, object state, ref StackCrawlMark stackMark, bool compressStack)
{
    bool flag = true;
    if (callBack == null)
    {
        throw new ArgumentNullException("WaitCallback");
    }
    EnsureVMInitialized();
    if (ThreadPoolGlobals.useNewWorkerPool)
    {
        try
        {
            return flag;
        }
        finally
        {
            QueueUserWorkItemCallback callback = new QueueUserWorkItemCallback(callBack, state, compressStack, ref stackMark);
            ThreadPoolGlobals.workQueue.Enqueue(callback, true);
            flag = true;
        }
    }
    // code below here removed
}

try/finally 块给我的印象是非常单一的 C#。为什么要这样写?如果你摆脱了 try/finally 并将 return 移到最后有什么区别?

我了解 Reflector 的工作原理,并且这可能不是原始来源。如果您认为是这样,您能否建议原始来源可能是什么?

【问题讨论】:

  • 您可能想查看该部分代码的 IL;我的猜测是反射器以一种有趣的方式反编译使用了一些微优化。

标签: c# threadpool idioms


【解决方案1】:

Microsoft 已将源代码发布到 .NET - 尽管由于浏览更方便,我仍然使用 Reflector。这是 .NET 4.0 的实际代码 sn-p。

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

【讨论】:

【解决方案2】:

实际上,Jeffrey Richter 的书“CLR via C#”中描述了这个空的 try 块和 finally 块模式中的代码。 问题是,如果出现问题并且线程被中止,finally 块保证执行。至少它们比 try 块更有可能执行。有关更多详细信息,您应该查看所提到的书中描述异常和错误处理的部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多