-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Async method lifetime + FAQ enrichment #53158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
BillWagner
wants to merge
1
commit into
dotnet:main
Choose a base branch
from
BillWagner:async-aweigh-6
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
docs/standard/asynchronous-programming-patterns/keeping-async-methods-alive.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| --- | ||
| title: "Keeping async methods alive" | ||
| description: Learn how to avoid lifetime bugs in fire-and-forget async code by keeping task ownership explicit, observing failures, and coordinating shutdown. | ||
| ms.date: 04/15/2026 | ||
| ai-usage: ai-assisted | ||
| dev_langs: | ||
| - "csharp" | ||
| - "vb" | ||
| helpviewer_keywords: | ||
| - "fire-and-forget" | ||
| - "async lifetime" | ||
| - "unobserved task exception" | ||
| - "background task tracking" | ||
| - "TAP best practices" | ||
| --- | ||
| # Keeping async methods alive | ||
|
|
||
| Fire-and-forget work is easy to start and easy to lose. If you start an asynchronous operation and drop the returned <xref:System.Threading.Tasks.Task>, you lose visibility into completion, cancellation, and failures. | ||
|
|
||
| Most lifetime bugs in async code are ownership bugs, not compiler bugs. The `async` state machine and its `Task` stay alive while work is still reachable through continuations. Problems happen when your app no longer tracks that work. | ||
|
|
||
| ## Why fire-and-forget causes lifetime bugs | ||
|
|
||
| When you start background work without tracking it, you create three risks: | ||
|
|
||
| - The operation can fail, and nobody observes the exception. | ||
| - The process or host can shut down before the operation finishes. | ||
| - The operation can outlive the object or scope that was meant to control it. | ||
|
|
||
| Use fire-and-forget only when the work is truly optional and failure is acceptable. | ||
|
|
||
| ## Bad and good fire-and-forget patterns | ||
|
|
||
| The following example starts untracked work and then shows a tracked alternative: | ||
|
|
||
| :::code language="csharp" source="./snippets/keeping-async-methods-alive/csharp/Program.cs" id="FireAndForgetPitfall"::: | ||
| :::code language="vb" source="./snippets/keeping-async-methods-alive/vb/Program.vb" id="FireAndForgetPitfall"::: | ||
|
|
||
| :::code language="csharp" source="./snippets/keeping-async-methods-alive/csharp/Program.cs" id="FireAndForgetFix"::: | ||
| :::code language="vb" source="./snippets/keeping-async-methods-alive/vb/Program.vb" id="FireAndForgetFix"::: | ||
|
|
||
| Track long-running work in an owner component and await tracked tasks during shutdown. | ||
|
|
||
| ## Keep ownership explicit | ||
|
|
||
| Prefer one of these ownership models: | ||
|
|
||
| - Return the `Task` and require callers to await it. | ||
| - Track background tasks in a dedicated owner service. | ||
| - Use a host-managed background abstraction so the host owns lifetime. | ||
|
|
||
| If work must continue after the caller returns, transfer ownership explicitly. For example, hand the task to a tracker that logs errors and participates in shutdown. | ||
|
|
||
| ## Surface exceptions from background tasks | ||
|
|
||
| Dropped tasks can fail silently until finalization and unobserved-exception handling occurs. That timing is non-deterministic and too late for normal request or workflow handling. | ||
|
|
||
| Attach observation logic when you queue background work. At minimum, log failures in a continuation. Prefer a centralized tracker so every queued operation gets the same policy. | ||
|
|
||
| For exception propagation details, see [Task exception handling](task-exception-handling.md). | ||
|
|
||
| ## Coordinate cancellation and shutdown | ||
|
|
||
| Tie background work to a cancellation token that represents app or operation lifetime. During shutdown: | ||
|
|
||
| 1. Stop accepting new work. | ||
| 1. Signal cancellation. | ||
| 1. Await tracked tasks with a bounded timeout. | ||
| 1. Log incomplete operations. | ||
|
|
||
| This flow keeps shutdown predictable and prevents partial writes or orphaned operations. | ||
|
|
||
| ## FAQ: Can the GC collect an async method before it finishes? | ||
|
|
||
| The runtime keeps the async state machine alive while continuations still reference it. You usually don't lose an in-flight async operation to garbage collection of the state machine itself. | ||
|
|
||
| You still can lose correctness if you lose ownership of the returned task, dispose required resources early, or let the process end before completion. Focus on task ownership and coordinated shutdown. | ||
|
|
||
| ## See also | ||
|
|
||
| - [Task-based asynchronous pattern (TAP)](task-based-asynchronous-pattern-tap.md) | ||
| - [Consuming the Task-based Asynchronous Pattern](consuming-the-task-based-asynchronous-pattern.md) | ||
| - [Common async/await bugs](common-async-bugs.md) | ||
| - [ExecutionContext and SynchronizationContext](executioncontext-synchronizationcontext.md) | ||
| - [Task exception handling](task-exception-handling.md) |
10 changes: 10 additions & 0 deletions
10
...ming-patterns/snippets/keeping-async-methods-alive/csharp/KeepingAsyncMethodsAlive.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| </Project> |
85 changes: 85 additions & 0 deletions
85
.../asynchronous-programming-patterns/snippets/keeping-async-methods-alive/csharp/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| using System.Collections.Concurrent; | ||
|
|
||
| // <FireAndForgetPitfall> | ||
| public static class FireAndForgetPitfall | ||
| { | ||
| public static async Task RunAsync() | ||
| { | ||
| _ = Task.Run(async () => | ||
| { | ||
| await Task.Delay(100); | ||
| throw new InvalidOperationException("Background operation failed."); | ||
| }); | ||
|
|
||
| await Task.Delay(150); | ||
| Console.WriteLine("Caller finished without observing background completion."); | ||
| } | ||
| } | ||
| // </FireAndForgetPitfall> | ||
|
|
||
| public sealed class BackgroundTaskTracker | ||
| { | ||
| private readonly ConcurrentDictionary<int, Task> _inFlight = new(); | ||
|
|
||
| public void Track(Task operationTask, string name) | ||
| { | ||
| int id = operationTask.Id; | ||
| _inFlight[id] = operationTask; | ||
|
|
||
| _ = operationTask.ContinueWith(completedTask => | ||
| { | ||
| _inFlight.TryRemove(id, out _); | ||
|
|
||
| if (completedTask.IsFaulted) | ||
| { | ||
| Console.WriteLine($"{name} failed: {completedTask.Exception?.GetBaseException().Message}"); | ||
| } | ||
| }, TaskScheduler.Default); | ||
| } | ||
|
|
||
| public Task DrainAsync() | ||
| { | ||
| Task[] snapshot = _inFlight.Values.ToArray(); | ||
| return snapshot.Length == 0 ? Task.CompletedTask : Task.WhenAll(snapshot); | ||
| } | ||
| } | ||
|
|
||
| // <FireAndForgetFix> | ||
| public static class FireAndForgetFix | ||
| { | ||
| public static async Task RunAsync(BackgroundTaskTracker tracker) | ||
| { | ||
| Task backgroundTask = Task.Run(async () => | ||
| { | ||
| await Task.Delay(100); | ||
| throw new InvalidOperationException("Background operation failed."); | ||
| }); | ||
|
|
||
| tracker.Track(backgroundTask, "Cache refresh"); | ||
|
|
||
| try | ||
| { | ||
| await tracker.DrainAsync(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Console.WriteLine($"Drain observed failure: {ex.GetBaseException().Message}"); | ||
| } | ||
| } | ||
| } | ||
| // </FireAndForgetFix> | ||
|
|
||
| public static class Program | ||
| { | ||
| public static async Task Main() | ||
| { | ||
| Console.WriteLine("--- Pitfall ---"); | ||
| await FireAndForgetPitfall.RunAsync(); | ||
|
|
||
| Console.WriteLine("--- Fix ---"); | ||
| var tracker = new BackgroundTaskTracker(); | ||
| await FireAndForgetFix.RunAsync(tracker); | ||
|
|
||
| Console.WriteLine("Done."); | ||
| } | ||
| } |
9 changes: 9 additions & 0 deletions
9
...gramming-patterns/snippets/keeping-async-methods-alive/vb/KeepingAsyncMethodsAlive.vbproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <RootNamespace>KeepingAsyncMethodsAlive</RootNamespace> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| </PropertyGroup> | ||
|
|
||
| </Project> |
76 changes: 76 additions & 0 deletions
76
...dard/asynchronous-programming-patterns/snippets/keeping-async-methods-alive/vb/Program.vb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| Imports System.Collections.Concurrent | ||
|
|
||
| ' <FireAndForgetPitfall> | ||
| Public Module FireAndForgetPitfall | ||
| Public Async Function RunAsync() As Task | ||
| Dim discardedTask As Task = Task.Run(Async Function() | ||
| Await Task.Delay(100) | ||
| Throw New InvalidOperationException("Background operation failed.") | ||
| End Function) | ||
|
|
||
| Await Task.Delay(150) | ||
| Console.WriteLine("Caller finished without observing background completion.") | ||
| End Function | ||
| End Module | ||
| ' </FireAndForgetPitfall> | ||
|
|
||
| Public NotInheritable Class BackgroundTaskTracker | ||
| Private ReadOnly _inFlight As New ConcurrentDictionary(Of Integer, Task)() | ||
|
|
||
| Public Sub Track(operationTask As Task, name As String) | ||
| Dim id As Integer = operationTask.Id | ||
| _inFlight(id) = operationTask | ||
|
|
||
| Dim continuationTask As Task = operationTask.ContinueWith(Sub(completedTask) | ||
| Dim removedTask As Task = Nothing | ||
| _inFlight.TryRemove(id, removedTask) | ||
|
|
||
| If completedTask.IsFaulted Then | ||
| Console.WriteLine($"{name} failed: {completedTask.Exception.GetBaseException().Message}") | ||
| End If | ||
| End Sub, | ||
| TaskScheduler.Default) | ||
| End Sub | ||
|
|
||
| Public Function DrainAsync() As Task | ||
| Dim snapshot As Task() = _inFlight.Values.ToArray() | ||
|
|
||
| If snapshot.Length = 0 Then | ||
| Return Task.CompletedTask | ||
| End If | ||
|
|
||
| Return Task.WhenAll(snapshot) | ||
| End Function | ||
| End Class | ||
|
|
||
| ' <FireAndForgetFix> | ||
| Public Module FireAndForgetFix | ||
| Public Async Function RunAsync(tracker As BackgroundTaskTracker) As Task | ||
| Dim backgroundTask As Task = Task.Run(Async Function() | ||
| Await Task.Delay(100) | ||
| Throw New InvalidOperationException("Background operation failed.") | ||
| End Function) | ||
|
|
||
| tracker.Track(backgroundTask, "Cache refresh") | ||
|
|
||
| Try | ||
| Await tracker.DrainAsync() | ||
| Catch ex As Exception | ||
| Console.WriteLine($"Drain observed failure: {ex.GetBaseException().Message}") | ||
| End Try | ||
| End Function | ||
| End Module | ||
| ' </FireAndForgetFix> | ||
|
|
||
| Module Program | ||
| Sub Main() | ||
| Console.WriteLine("--- Pitfall ---") | ||
| FireAndForgetPitfall.RunAsync().Wait() | ||
|
|
||
| Console.WriteLine("--- Fix ---") | ||
| Dim tracker As New BackgroundTaskTracker() | ||
| FireAndForgetFix.RunAsync(tracker).Wait() | ||
|
|
||
| Console.WriteLine("Done.") | ||
| End Sub | ||
| End Module |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reading this as layman rises the question what it that pattern?
Should it get explained, linked to some article, etc.?