CKTIS / C#
System.Threading.Tasks.TaskCompletionSource: practical reference
System.Threading.Tasks.TaskCompletionSource: practical reference: TaskCompletionSource<T> lets a producer complete a Task<T> manually.
Version: .NET API; verified against .NET 10 reference surface
Syntax
System.Threading.Tasks.TaskCompletionSource /* select a documented member or constructor */TaskCompletionSource lets a producer complete a Task manually.
Use it to adapt callbacks and events to the task model.
Prefer RunContinuationsAsynchronously so a callback cannot perform heavy work inside SetResult.
A second Set* throws; TrySet* returns false if completion already occurred.
The complete program actually uses System.Threading.Tasks.TaskCompletionSource; its exact expected stdout is 9.
Examples
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;
var source = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
source.SetResult(9);
Console.WriteLine(await source.Task);
Result
9
The complete program actually uses `System.Threading.Tasks.TaskCompletionSource`; its exact expected stdout is `9`.