Skip to content

[API Proposal]: ExecutionContext.Default #121098

@stephentoub

Description

@stephentoub

Background and motivation

Not very commonly but now and then, a developer finds themselves wanting to escape from the current ExecutionContext. For asynchronous work, this can be done via a method like ThreadPool.UnsafeQueueUserWorkItem, which puts work onto the ThreadPool explicitly without flowing the current ExecutionContext, such that the work item will run in what's effectively the default context. But for synchronous work, there isn't a great option. Typical guidance to such a dev, if they're able, is to capture an ExecutionContext at app startup, and then use that captured context with ExecutionContext.Run when they need a default.

API Proposal

namespace System.Threading;

public sealed class ExecutionContext
{
+   public static ExecutionContext Default { get; }
}

(Default actually already exists, but as an internal field rather than as a public property.)

API Usage

// Escape current context
ExecutionContext.Run(ExecutionContext.Default, state => { ... }, state);

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.ThreadinguntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions