Codectionary / Developer documentation / C#

Bridge Completion Signals with TaskCompletionSource

Expose a Task whose result, failure or cancellation is controlled by a callback-based operation.

Read the syntax

Expose a Task whose result, failure or cancellation is controlled by a callback-based operation.

The callback sets the result but does not create another thread.

What it is and why to use it

An existing API may signal completion through a callback rather than returning a Task. TaskCompletionSource<T> lets an adapter expose a Task to await while completing it when that signal arrives. It does not start work or create a background thread. Ordinary asynchronous methods should normally return their own Task without adding this bridge unnecessarily.

How it works

Create the source, pass its Task to consumers, and complete it through SetResult, SetException or cancellation methods. TrySet variants return false if another signal already completed the Task. RunContinuationsAsynchronously prevents registered continuations from running inline in the completing call, reducing surprising reentrancy. A complete adapter also handles cancellation, errors and callback unsubscription.

Common mistakes and limitations

Do not leave a completion source without a path to complete, fail or cancel it. Do not assume callbacks occur once or only after the adapter returns. Avoid completing tasks while holding locks when arbitrary continuations could otherwise run inline. Prefer existing task-based APIs when available.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

var completion = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);

Examples

Adapt a simple callback result

Use an in-process callback that may complete immediately.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var completion = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
Begin(value => completion.TrySetResult(value));
Console.WriteLine(await completion.Task);
static void Begin(Action<int> finished) { finished(42); }
  1. The Task exists before Begin is called, so an immediate callback is safe.
  2. The callback sets the result but does not create another thread.
  3. Await retrieves 42 whether completion happened before or after reaching the await. This minimal adapter has only a success signal; real APIs need other terminal paths.
  4. Expected output: 42
  5. Design every completion, failure and cancellation path.

Handle duplicate completion signals

Observe that only the first terminal result wins.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var completion = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
Console.WriteLine(completion.TrySetResult("First"));
Console.WriteLine(completion.TrySetResult("Second"));
Console.WriteLine(await completion.Task);
  1. The first TrySetResult completes the task and returns true.
  2. The second finds an already-completed task and returns false instead of changing its result.
  3. The consumer receives First. Decide whether duplicate external signals should also be recorded as an integration error.
  4. Expected output: True False First
  5. Design every completion, failure and cancellation path.

Best practices

  • Design every completion, failure and cancellation path.
  • Prefer TrySet when multiple external signals may race.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading