ThreadPool.QueueUserWorkItem preferLocal 有什么用?

What is ThreadPool.QueueUserWorkItem preferLocal for?

我刚刚注意到 .NET 核心引入了 Threadpool.QueueUserWorkItem 的重载,它接受一个名为 'preferlocal' 的布尔值并允许我传递一个类型安全的状态对象(它有一个通用的参数)

MSDN documentation 目前不完整,看起来像这样(为了后代 - 将来可能会更新):

QueueUserWorkItem<TState>(Action<TState>, TState, Boolean)
C#

public static bool QueueUserWorkItem<TState> (Action<TState> callBack, TState state, bool preferLocal);

Type Parameters TState

Parameters
callBack Action<TState>

state

preferLocal Boolean

Returns
Boolean

这个布尔值 (preferLocal) 的作用是什么?它将如何影响我的代码?

看起来它是由 this pull request which links to this issue 添加的(两个 Github 链接,分别是 "Add ThreadPool.QueueUserWorkItem(..., bool preferLocal)/#14214" 和 "Add QueueUserWorkItem for local threadpool queues/#12442")。

问题描述为:

ThreadPool.QueueUserWorkItem always queues to the global queue; however it would be good to have the option to be able to queue to the current threadpool thread's local queue when a threadpool thread queues extra work items.

Rationale and Usage

  • Reduced contention on the global queue when many threads are queuing
  • Potentially hotter more local data when the queuing work item completes
  • Take advantage of threadpool's task stealing
  • (i.e. Similar to Task's rational for doing it for child Tasks)

对我来说,遗憾的是最新的在线文档(MSDN 文档是从中生成的)不是拉取请求的先决条件。


最初构建线程池时,它只有一个工作队列要完成。然而,当所有 Task 优点都被引入框架时,他们借此机会引入了线程本地队列(和 work stealing)以及现在更名为全局队列的队列。看起来这是允许对这些队列进行特定访问的清理工作。