Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

System.Threading.Tasks.TaskCompletionSource: odniesienie praktyczne

System.Threading.Tasks.TaskCompletionSource: odniesienie praktyczne: TaskCompletionSource<T> pozwala producentowi ręcznie zakończyć Task<T>.

Wersja: .NET API; verified against .NET 10 reference surface

Składnia

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

TaskCompletionSource pozwala producentowi ręcznie zakończyć Task.

Stosuj do adaptacji callbacków i zdarzeń na model task.

Preferuj RunContinuationsAsynchronously, by callback nie wykonał ciężkiej pracy wewnątrz SetResult.

Drugie Set* zgłasza wyjątek; TrySet* zwraca false przy wcześniejszym zakończeniu.

Kompletny program rzeczywiście używa System.Threading.Tasks.TaskCompletionSource; oczekiwany stdout to dokładnie 9.

Przykłady

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

Wynik

9

Kompletny program rzeczywiście używa `System.Threading.Tasks.TaskCompletionSource`; oczekiwany stdout to dokładnie `9`.

Źródła