Skip to content

Add Thread.UnsafeStart to avoid capturing the ExecutionContext  #46594

@davidfowl

Description

@davidfowl

Background and Motivation

We added UnsafeStart in this PR #46181 because we needed to lazily create thread pool threads and the timer thread on the default execution context. UnsafeStart avoids capturing the current execution context and restoring it when the thread runs. There are other places where we create threads that could use similar logic:

These are places that should start on the default execution context.

Proposed API

namespace System.Threading
{
     public class Thread 
     {
+       void UnsafeStart();
+       void UnsafeStart(object? parameter);
     }

Usage Examples

var local = new AsyncLocal<int>();
local.Value = 10;
var thread= new Thead(() => 
{
    var value = local.Value;
    while (true)
    {
         Console.WriteLine(value++);
         Thread.Sleep(5000);
    }
});

thread.UnsafeStart();

Alternative Designs

Passing a boolean to the thread constructor but that seemed like a bad idea since Start is the thing capturing the execution.

Risks

None.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions