Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/navigate/advanced-programming/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ items:
href: ../../standard/asynchronous-programming-patterns/common-async-bugs.md
- name: Async lambda pitfalls
href: ../../standard/asynchronous-programming-patterns/async-lambda-pitfalls.md
- name: Keeping async methods alive
href: ../../standard/asynchronous-programming-patterns/keeping-async-methods-alive.md
- name: Event-based asynchronous pattern (EAP)
items:
- name: Documentation overview
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,5 +117,6 @@ Storing the result in a variable suppresses the warning but doesn't fix the unde

- [Task-based asynchronous pattern (TAP)](task-based-asynchronous-pattern-tap.md)
- [Async lambda pitfalls](async-lambda-pitfalls.md)
- [Keeping async methods alive](keeping-async-methods-alive.md)
- [Asynchronous wrappers for synchronous methods](async-wrappers-for-synchronous-methods.md)
- [Synchronous wrappers for asynchronous methods](synchronous-wrappers-for-asynchronous-methods.md)
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ Task.Run(async delegate
await someTask.ConfigureAwait(continueOnCapturedContext:false);
```

### FAQ: Awaitables, ConfigureAwait, and SynchronizationContext

`await` works with awaitable types, not just <xref:System.Threading.Tasks.Task>. A type is awaitable if it provides a compatible `GetAwaiter` pattern. In most public APIs, return <xref:System.Threading.Tasks.Task>, <xref:System.Threading.Tasks.Task`1>, <xref:System.Threading.Tasks.ValueTask>, or <xref:System.Threading.Tasks.ValueTask`1>, and use custom awaitables only for specialized scenarios.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if it provides a compatible GetAwaiter pattern

Reading this as layman rises the question what it that pattern?
Should it get explained, linked to some article, etc.?


Use <xref:System.Threading.Tasks.Task.ConfigureAwait*> when the continuation doesn't need the caller's context. In app code that updates a UI, context capture is often required. In reusable library code, `ConfigureAwait(false)` is usually preferred because it avoids unnecessary context hops and reduces deadlock risk for callers that block.

`ConfigureAwait(false)` changes continuation scheduling, not <xref:System.Threading.ExecutionContext> flow. For a deeper explanation of context behavior, see [ExecutionContext and SynchronizationContext](executioncontext-synchronizationcontext.md).

## Canceling an Asynchronous Operation

Starting with .NET Framework 4, TAP methods that support cancellation provide at least one overload that accepts a cancellation token (<xref:System.Threading.CancellationToken> object).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ You can implement the Task-based Asynchronous Pattern (TAP) in three ways: by us

Starting with .NET Framework 4.5, any method that is attributed with the `async` keyword (`Async` in Visual Basic) is considered an asynchronous method, and the C# and Visual Basic compilers perform the necessary transformations to implement the method asynchronously by using TAP. An asynchronous method should return either a <xref:System.Threading.Tasks.Task?displayProperty=nameWithType> or a <xref:System.Threading.Tasks.Task`1?displayProperty=nameWithType> object. For the latter, the body of the function should return a `TResult`, and the compiler ensures that this result is made available through the resulting task object. Similarly, any exceptions that go unhandled within the body of the method are marshalled to the output task and cause the resulting task to end in the <xref:System.Threading.Tasks.TaskStatus.Faulted?displayProperty=nameWithType> state. The exception to this rule is when an <xref:System.OperationCanceledException> (or derived type) goes unhandled, in which case the resulting task ends in the <xref:System.Threading.Tasks.TaskStatus.Canceled?displayProperty=nameWithType> state.

### FAQ: Task.Start and Task disposal

Use <xref:System.Threading.Tasks.Task.Start*> only for tasks explicitly created with a <xref:System.Threading.Tasks.Task> constructor that are still in the `Created` state. Public TAP methods should return active tasks, so callers shouldn't need to call `Start`.

In most TAP code, don't dispose tasks. A <xref:System.Threading.Tasks.Task> doesn't hold unmanaged resources in the typical case, and disposing every task adds overhead without practical benefit. Dispose only when specific APIs or measurements show a need.

If you start background work that outlives the immediate call path, keep ownership explicit and track completion. For more guidance, see [Keeping async methods alive](keeping-async-methods-alive.md).

### Generating TAP methods manually

You may implement the TAP pattern manually for better control over implementation. The compiler relies on the public surface area exposed from the <xref:System.Threading.Tasks?displayProperty=nameWithType> namespace and supporting types in the <xref:System.Runtime.CompilerServices?displayProperty=nameWithType> namespace. To implement the TAP yourself, you create a <xref:System.Threading.Tasks.TaskCompletionSource`1> object, perform the asynchronous operation, and when it completes, call the <xref:System.Threading.Tasks.TaskCompletionSource`1.SetResult*>, <xref:System.Threading.Tasks.TaskCompletionSource`1.SetException*>, or <xref:System.Threading.Tasks.TaskCompletionSource`1.SetCanceled*> method, or the `Try` version of one of these methods. When you implement a TAP method manually, you must complete the resulting task when the represented asynchronous operation completes. For example:
Expand Down
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)
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>
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.");
}
}
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>
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
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ TAP uses a single method to represent the initiation and completion of an asynch

For examples of how the TAP syntax differs from the syntax used in legacy asynchronous programming patterns such as the Asynchronous Programming Model (APM) and the Event-based Asynchronous Pattern (EAP), see [Asynchronous Programming Patterns](index.md).

### FAQ: async behavior, return types, and naming

The `async` keyword doesn't force a method to run asynchronously on another thread. It enables `await`, and the method runs synchronously until it reaches an incomplete awaitable. If no incomplete awaitable is reached, the method can complete synchronously.

For most APIs, prefer these return types:

- Use <xref:System.Threading.Tasks.Task> for asynchronous operations that don't produce a value.
- Use <xref:System.Threading.Tasks.Task`1> for asynchronous operations that produce a value.
- Use <xref:System.Threading.Tasks.ValueTask> or <xref:System.Threading.Tasks.ValueTask`1> only when measurements show allocation pressure and when consumers can handle the extra usage constraints.

Keep TAP naming predictable:

- Use the `Async` suffix for methods that return awaitable types.
- Don't append `Async` to synchronous methods.
- Keep existing public names stable, and add new TAP overloads instead of renaming established APIs unless you're already making a breaking change.

## Initiating an asynchronous operation

An asynchronous method that is based on TAP can do a small amount of work synchronously, such as validating arguments and initiating the asynchronous operation, before it returns the resulting task. Synchronous work should be kept to the minimum so the asynchronous method can return quickly. Reasons for a quick return include:
Expand All @@ -54,6 +70,8 @@ TAP uses a single method to represent the initiation and completion of an asynch

All other tasks begin their life cycle in a hot state, which means that the asynchronous operations they represent have already been initiated and their task status is an enumeration value other than <xref:System.Threading.Tasks.TaskStatus.Created?displayProperty=nameWithType>. All tasks that are returned from TAP methods must be activated. **If a TAP method internally uses a task's constructor to instantiate the task to be returned, the TAP method must call <xref:System.Threading.Tasks.Task.Start*> on the <xref:System.Threading.Tasks.Task> object before returning it.** Consumers of a TAP method may safely assume that the returned task is active and shouldn't try to call <xref:System.Threading.Tasks.Task.Start*> on any <xref:System.Threading.Tasks.Task> that is returned from a TAP method. Calling <xref:System.Threading.Tasks.Task.Start*> on an active task results in an <xref:System.InvalidOperationException> exception.

For guidance on fire-and-forget lifetime and ownership concerns after task activation, see [Keeping async methods alive](keeping-async-methods-alive.md).

## Cancellation (optional)

In TAP, cancellation is optional for both asynchronous method implementers and asynchronous method consumers. If an operation allows cancellation, it exposes an overload of the asynchronous method that accepts a cancellation token (<xref:System.Threading.CancellationToken> instance). By convention, the parameter is named `cancellationToken`.
Expand Down
Loading