Jay
Jay

Reputation: 10128

What is ThreadPool.QueueUserWorkItem preferLocal for?

I've just noticed that .NET core introduces an overload of Threadpool.QueueUserWorkItem which takes a boolean called 'preferlocal' and allows me to pass through a type-safe state object (it has a generic parameter)

The MSDN documentation is currently incomplete and looks like this (for posterity - it may be updated in the future):

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

What is this boolean (preferLocal) for and how will it affect my code?

Upvotes: 7

Views: 1489

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239724

It looks like it was added by this pull request which links to this issue (both Github links, "Add ThreadPool.QueueUserWorkItem(..., bool preferLocal)/#14214" and "Add QueueUserWorkItem for local threadpool queues/#12442", respectively).

The issue is described as:

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)

For me, it feels a pity that up to date in-line documentation (from which the MSDN documentation is generated) isn't a pre-requisite for pull requests.


When the Thread Pool was first built, it only had a single queue of work to be done. However, when all of the Task goodness was being plumbed into the framework, they took the opportunity to introduce thread-local queues (and work stealing) alongside what was now renamed the global queue. It looks like this is clean-up work to allow specific access to these queues.

Upvotes: 12

Related Questions