dotnet / dotnet/runtime

[API Proposal]: ExecutionContext.Default

Open
#121,098 5 comments 5 reactions 0 assignees View on GitHub
api-suggestion area-System.Threading
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### 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

```diff
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

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

### Alternative Designs

_No response_

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.