AsyncUtils
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Newtonsoft.Json.Utilities
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
internal static class AsyncUtils
{
public static readonly Task<bool> False = Task.FromResult(false);
public static readonly Task<bool> True = Task.FromResult(true);
internal static readonly Task CompletedTask = Task.Delay(0);
internal static Task<bool> ToAsync(this bool value)
{
if (!value)
return False;
return True;
}
[System.Runtime.CompilerServices.NullableContext(2)]
public static Task CancelIfRequestedAsync(this CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return null;
return cancellationToken.FromCanceled();
}
[System.Runtime.CompilerServices.NullableContext(2)]
[return: System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})]
public static Task<T> CancelIfRequestedAsync<T>(this CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return null;
return cancellationToken.FromCanceled<T>();
}
public static Task FromCanceled(this CancellationToken cancellationToken)
{
return new Task(delegate {
}, cancellationToken);
}
public static Task<T> FromCanceled<[System.Runtime.CompilerServices.Nullable(2)] T>(this CancellationToken cancellationToken)
{
return new Task<T>((Func<T>)(() => default(T)), cancellationToken);
}
public static Task WriteAsync(this TextWriter writer, char value, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return writer.WriteAsync(value);
return cancellationToken.FromCanceled();
}
public static Task WriteAsync(this TextWriter writer, [System.Runtime.CompilerServices.Nullable(2)] string value, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return writer.WriteAsync(value);
return cancellationToken.FromCanceled();
}
public static Task WriteAsync(this TextWriter writer, char[] value, int start, int count, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return writer.WriteAsync(value, start, count);
return cancellationToken.FromCanceled();
}
public static Task<int> ReadAsync(this TextReader reader, char[] buffer, int index, int count, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return reader.ReadAsync(buffer, index, count);
return cancellationToken.FromCanceled<int>();
}
public static bool IsCompletedSuccessfully(this Task task)
{
return task.Status == TaskStatus.RanToCompletion;
}
}
}