Skip to content

Reset certain thread-local state after thread pool work item execution #16455

@GSPP

Description

@GSPP

It can sometimes happen by accident that a thread pool work item sets some thread-local state such as:

  • SynchronizationContext.Current
  • HostContext (used for HttpContext.Current)
  • Thread priority
  • Thread name
  • Thread culture
  • Thread principal
  • Others?

Failing to reset that state causes non-deterministic "leaks" that are very hard to diagnose. This is especially relevant in ASP.NET and in unit testing scenarios. The thread pool is a global process resource. Generally, code should play nice with such resources but bugs should not be catastrophic.

The .NET thread pool should reset all of these items (where practical) after the execution of each work item. I see no valid scenario why someone might want to set these values and have them persist because there is no way to make that deterministic.

Regarding the above items I could not find documentation that specifies which one of them are reset or are not reset. This behavior should be documented and contractually guaranteed.

Ideally, setting Thread properties should fail outright but that might not be possible for compatibility reasons.

The behavior changes proposed here should work for the legacy thread pool API as well as for the TPL.

I have not added the execution context and logical call context to the list because I lack the technical understanding to recommend anything about them. Maybe they should be reset as well.

I have not added ThreadStatic and other forms of thread-static variables because those are often useful for caching scenarios. Resetting them would be a bad idea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Threading

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions