// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace System.Threading.Tasks
{
///
/// Helpers for safely using Task libraries.
///
internal static class TaskHelpers
{
private static readonly Task _defaultCompleted = Task.FromResult(default(AsyncVoid));
private static readonly Task _completedTaskReturningNull = Task.FromResult(null);
///
/// Returns a canceled Task. The task is completed, IsCanceled = True, IsFaulted = False.
///
internal static Task Canceled()
{
return CancelCache.Canceled;
}
///
/// Returns a canceled Task of the given type. The task is completed, IsCanceled = True, IsFaulted = False.
///
internal static Task Canceled()
{
return CancelCache.Canceled;
}
///
/// Returns a completed task that has no result.
///
internal static Task Completed()
{
return _defaultCompleted;
}
///
/// Returns an error task. The task is Completed, IsCanceled = False, IsFaulted = True
///
internal static Task FromError(Exception exception)
{
return FromError(exception);
}
///
/// Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True
///
///
internal static Task FromError(Exception exception)
{
TaskCompletionSource tcs = new TaskCompletionSource();
tcs.SetException(exception);
return tcs.Task;
}
internal static Task NullResult()
{
return _completedTaskReturningNull;
}
///
/// Used as the T in a "conversion" of a Task into a Task{T}
///
private struct AsyncVoid
{
}
///
/// This class is a convenient cache for per-type cancelled tasks
///
private static class CancelCache
{
public static readonly Task Canceled = GetCancelledTask();
private static Task GetCancelledTask()
{
TaskCompletionSource tcs = new TaskCompletionSource();
tcs.SetCanceled();
return tcs.Task;
}
}
}
}