Skip to content

Add opt-in UniTaskScheduler.FlowExecutionContext for .NET - #732

Open
BiruLyuPG wants to merge 1 commit into
Cysharp:masterfrom
BiruLyuPG:flow-execution-context
Open

BiruLyuPG wants to merge 1 commit into
Cysharp:masterfrom
BiruLyuPG:flow-execution-context

Conversation

@BiruLyuPG

Copy link
Copy Markdown

Adds an opt-in setting so async UniTask methods on .NET restore the ExecutionContext as async Task does, letting AsyncLocal values survive an await. It is off by default, so nothing changes unless you set it.

Why

What changes

  • New UniTaskScheduler.FlowExecutionContext, under UNITASK_NETCORE only, default false.
  • When set, the builders capture the ExecutionContext at each await, and the pooled runners resume inside ExecutionContext.Run. A runner returned to the pool drops its context.
  • When set, Start runs the code before the first await inside AsyncTaskMethodBuilder.Start, so a write there stays in the method, as with async Task.
  • Unity builds are unchanged: every change is inside #if UNITASK_NETCORE.
  • The README's .NET Core section mentions the setting.

Cost

Each call has one suspending await, resumed inline, with an AsyncLocal set. 2M calls, best of 5, .NET 8.0.19, Apple M4 Pro:

stock master setting off setting on async Task<int>
async UniTask<int> 16.8 ns, 0 B 18.2 ns, 0 B 24.1 ns, 0 B 27.2 ns, 160 B
async UniTask 16.6 ns, 0 B 17.3 ns, 0 B 26.9 ns, 0 B

Tests

  • ExecutionContextTest has 5 tests and runs with the setting on, in a non-parallel collection. With the setting off, 4 of them fail. The 5th guards the Start change.
  • Full UniTask.NetCoreTests suite: 342/342.

🤖 Generated with Claude Code

When set (UNITASK_NETCORE only, default false), the async method builders capture the
ExecutionContext at each await, the pooled runners resume inside ExecutionContext.Run with it,
and Start runs the code before the first await inside AsyncTaskMethodBuilder.Start. An async
UniTask method then treats the context as async Task does, so AsyncLocal values survive an
await. Unset, and in Unity builds, behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant