Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / C#

System.Threading.Tasks.TaskCompletionSource: referencia práctica

System.Threading.Tasks.TaskCompletionSource: referencia práctica: TaskCompletionSource<T> permite a un productor completar manualmente un Task<T>.

Versión: .NET API; verified against .NET 10 reference surface

Sintaxis

System.Threading.Tasks.TaskCompletionSource /* select a documented member or constructor */

TaskCompletionSource permite a un productor completar manualmente un Task.

Úsalo para adaptar callbacks y eventos al modelo task.

Prefiere RunContinuationsAsynchronously para que un callback no haga trabajo pesado dentro de SetResult.

Un segundo Set* lanza una excepción; TrySet* devuelve false si ya se completó.

El programa completo usa realmente System.Threading.Tasks.TaskCompletionSource; su stdout esperado exacto es 9.

Ejemplos

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);

Resultado

9

El programa completo usa realmente `System.Threading.Tasks.TaskCompletionSource`; su stdout esperado exacto es `9`.

Fuentes