Class TplExtensions
- Namespace
- Microsoft.VisualStudio.Threading
- Assembly
- Microsoft.VisualStudio.Threading.dll
Extensions to the Task Parallel Library.
public static class TplExtensions
- Inheritance
-
TplExtensions
- Inherited Members
Fields
CanceledTask
A task that is already canceled.
[Obsolete("Use Task.FromCanceled instead.")]
public static readonly Task CanceledTask
Field Value
CompletedTask
A singleton completed task.
[Obsolete("Use Task.CompletedTask instead.")]
public static readonly Task CompletedTask
Field Value
FalseTask
A completed task with a false result.
public static readonly Task<bool> FalseTask
Field Value
TrueTask
A completed task with a true result.
public static readonly Task<bool> TrueTask
Field Value
Methods
AppendAction(Task, Action, TaskContinuationOptions, CancellationToken)
Schedules some action for execution at the conclusion of a task, regardless of the task's outcome.
public static Task AppendAction(this Task task, Action action, TaskContinuationOptions options = TaskContinuationOptions.None, CancellationToken cancellation = default)
Parameters
task
TaskThe task that should complete before the posted
action
is invoked.action
ActionThe action to execute after
task
has completed.options
TaskContinuationOptionsThe task continuation options to apply.
cancellation
CancellationTokenThe cancellation token that signals the continuation should not execute (if it has not already begun).
Returns
- Task
The task that will execute the action.
ApplyResultTo<T>(Task, TaskCompletionSource<T>)
Applies one task's results to another.
public static void ApplyResultTo<T>(this Task task, TaskCompletionSource<T> tcs)
Parameters
task
TaskThe task whose completion should be applied to another.
tcs
TaskCompletionSource<T>The task that should receive the completion status.
Type Parameters
T
The type of value returned by a task.
ApplyResultTo<T>(Task<T>, TaskCompletionSource<T>)
Applies one task's results to another.
public static void ApplyResultTo<T>(this Task<T> task, TaskCompletionSource<T> tcs)
Parameters
task
Task<T>The task whose completion should be applied to another.
tcs
TaskCompletionSource<T>The task that should receive the completion status.
Type Parameters
T
The type of value returned by a task.
AttachToParent(Task)
Creates a task that is attached to the parent task, but produces the same result as an existing task.
public static Task AttachToParent(this Task task)
Parameters
task
TaskThe task to wrap with an AttachedToParent task.
Returns
- Task
A task that is attached to parent.
AttachToParent<T>(Task<T>)
Creates a task that is attached to the parent task, but produces the same result as an existing task.
public static Task<T> AttachToParent<T>(this Task<T> task)
Parameters
task
Task<T>The task to wrap with an AttachedToParent task.
Returns
- Task<T>
A task that is attached to parent.
Type Parameters
T
The type of value produced by the task.
FollowCancelableTaskToCompletion<T>(Func<Task<T>>, CancellationToken, TaskCompletionSource<T>?)
Gets a task that will eventually produce the result of another task, when that task finishes. If that task is instead canceled, its successor will be followed for its result, iteratively.
public static Task<T> FollowCancelableTaskToCompletion<T>(Func<Task<T>> taskToFollow, CancellationToken ultimateCancellation, TaskCompletionSource<T>? taskThatFollows = null)
Parameters
taskToFollow
Func<Task<T>>The task whose result should be returned by the following task.
ultimateCancellation
CancellationTokenA token whose cancellation signals that the following task should be cancelled.
taskThatFollows
TaskCompletionSource<T>The TaskCompletionSource whose task is to follow. Leave at null for a new task to be created.
Returns
- Task<T>
The following task.
Type Parameters
T
The type of value returned by the task.
Forget(Task?)
Consumes a task and doesn't do anything with it. Useful for fire-and-forget calls to async methods within async methods.
public static void Forget(this Task? task)
Parameters
task
TaskThe task whose result is to be ignored.
Forget(ValueTask)
Consumes a ValueTask and allows it to be recycled, if applicable. Useful for fire-and-forget calls to async methods within async methods. NOTE: APIs should not generally return ValueTask if callers aren't 99.9999% likely to await the result immediately.
public static void Forget(this ValueTask task)
Parameters
task
ValueTaskThe task whose result is to be ignored.
Forget<T>(ValueTask<T>)
Consumes a ValueTask and allows it to be recycled, if applicable. Useful for fire-and-forget calls to async methods within async methods. NOTE: APIs should not generally return ValueTask<TResult> if callers aren't 99.9999% likely to await the result immediately.
public static void Forget<T>(this ValueTask<T> task)
Parameters
task
ValueTask<T>The task whose result is to be ignored.
Type Parameters
T
The type of value produced by the
task
.
InvokeAsync(AsyncEventHandler?, object?, EventArgs)
Invokes asynchronous event handlers, returning a task that completes when all event handlers have been invoked. Each handler is fully executed (including continuations) before the next handler in the list is invoked.
public static Task InvokeAsync(this AsyncEventHandler? handlers, object? sender, EventArgs args)
Parameters
handlers
AsyncEventHandlerThe event handlers. May be null.
sender
objectThe event source.
args
EventArgsThe event argument.
Returns
- Task
The task that completes when all handlers have completed.
Exceptions
- AggregateException
Thrown if any handlers fail. It contains a collection of all failures.
InvokeAsync<TEventArgs>(AsyncEventHandler<TEventArgs>?, object?, TEventArgs)
Invokes asynchronous event handlers, returning a task that completes when all event handlers have been invoked. Each handler is fully executed (including continuations) before the next handler in the list is invoked.
public static Task InvokeAsync<TEventArgs>(this AsyncEventHandler<TEventArgs>? handlers, object? sender, TEventArgs args)
Parameters
handlers
AsyncEventHandler<TEventArgs>The event handlers. May be null.
sender
objectThe event source.
args
TEventArgsThe event argument.
Returns
- Task
The task that completes when all handlers have completed. The task is faulted if any handlers throw an exception.
Type Parameters
TEventArgs
The type of argument passed to each handler.
Exceptions
- AggregateException
Thrown if any handlers fail. It contains a collection of all failures.
NoThrowAwaitable(Task, bool)
Returns an awaitable for the specified task that will never throw, even if the source task faults or is canceled.
public static TplExtensions.NoThrowTaskAwaitable NoThrowAwaitable(this Task task, bool captureContext = true)
Parameters
task
TaskThe task whose completion should signal the completion of the returned awaitable.
captureContext
boolif set to true the continuation will be scheduled on the caller's context; false to always execute the continuation on the threadpool.
Returns
- TplExtensions.NoThrowTaskAwaitable
An awaitable.
NoThrowAwaitable(ValueTask, bool)
Returns an awaitable for the specified task that will never throw, even if the source task faults or is canceled.
public static TplExtensions.NoThrowValueTaskAwaitable NoThrowAwaitable(this ValueTask task, bool captureContext = true)
Parameters
task
ValueTaskThe task whose completion should signal the completion of the returned awaitable.
captureContext
boolif set to true the continuation will be scheduled on the caller's context; false to always execute the continuation on the threadpool.
Returns
- TplExtensions.NoThrowValueTaskAwaitable
An awaitable.
NoThrowAwaitable<TResult>(ValueTask<TResult>, bool)
Returns an awaitable for the specified task that will never throw, even if the source task faults or is canceled.
public static TplExtensions.NoThrowValueTaskAwaitable<TResult> NoThrowAwaitable<TResult>(this ValueTask<TResult> task, bool captureContext = true)
Parameters
task
ValueTask<TResult>The task whose completion should signal the completion of the returned awaitable.
captureContext
boolif set to true the continuation will be scheduled on the caller's context; false to always execute the continuation on the threadpool.
Returns
- TplExtensions.NoThrowValueTaskAwaitable<TResult>
An awaitable.
Type Parameters
TResult
The type of the result.
Remarks
The awaitable returned by this method does not provide access to the result of a successfully-completed ValueTask<TResult>. To await without throwing and use the resulting value, the following pattern may be used:
var methodValueTask = MethodAsync().Preserve();
await methodValueTask.NoThrowAwaitable(true);
if (methodValueTask.IsCompletedSuccessfully)
{
var result = methodValueTask.Result;
}
else
{
var exception = methodValueTask.AsTask().Exception.InnerException;
}
ToApm(Task, AsyncCallback?, object?)
Converts a TPL task to the APM Begin-End pattern.
public static Task ToApm(this Task task, AsyncCallback? callback, object? state)
Parameters
task
TaskThe task that came from the async method.
callback
AsyncCallbackThe optional callback to invoke when the task is completed.
state
objectThe state object provided by the caller of the Begin method.
Returns
- Task
A task (that implements IAsyncResult that should be returned from the Begin method.
ToApm<TResult>(Task<TResult>, AsyncCallback?, object?)
Converts a TPL task to the APM Begin-End pattern.
public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback? callback, object? state)
Parameters
task
Task<TResult>The task that came from the async method.
callback
AsyncCallbackThe optional callback to invoke when the task is completed.
state
objectThe state object provided by the caller of the Begin method.
Returns
- Task<TResult>
A task (that implements IAsyncResult that should be returned from the Begin method.
Type Parameters
TResult
The result value to be returned from the End method.
ToTask(WaitHandle, int, CancellationToken)
Creates a TPL Task that returns true when a WaitHandle is signaled or returns false if a timeout occurs first.
public static Task<bool> ToTask(this WaitHandle handle, int timeout = -1, CancellationToken cancellationToken = default)
Parameters
handle
WaitHandleThe handle whose signal triggers the task to be completed. Do not use a Mutex here.
timeout
intThe timeout (in milliseconds) after which the task will return false if the handle is not signaled by that time.
cancellationToken
CancellationTokenA token whose cancellation will cause the returned Task to immediately complete in a canceled state.
Returns
- Task<bool>
A Task that completes when the handle is signaled or times out, or when the caller's cancellation token is canceled. If the task completes because the handle is signaled, the task's result is true. If the task completes because the handle is not signaled prior to the timeout, the task's result is false.
Remarks
The completion of the returned task is asynchronous with respect to the code that actually signals the wait handle.
WaitWithoutInlining(Task)
Wait on a task without possibly inlining it to the current thread.
public static void WaitWithoutInlining(this Task task)
Parameters
task
TaskThe task to wait on.
WithTimeout(Task, TimeSpan)
Returns a task that completes as the original task completes or when a timeout expires, whichever happens first.
public static Task WithTimeout(this Task task, TimeSpan timeout)
Parameters
Returns
- Task
A task that completes with the result of the specified
task
or faults with a TimeoutException iftimeout
elapses first.
WithTimeout<T>(Task<T>, TimeSpan)
Returns a task that completes as the original task completes or when a timeout expires, whichever happens first.
public static Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout)
Parameters
Returns
- Task<T>
A task that completes with the result of the specified
task
or faults with a TimeoutException iftimeout
elapses first.
Type Parameters
T
The type of value returned by the original task.