// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Threading; using System.Threading.Tasks; namespace Squidex.Infrastructure.Tasks { public static class TaskExtensions { private static readonly Action IgnoreTaskContinuation = t => { var ignored = t.Exception; }; public static void Forget(this Task task) { if (task.IsCompleted) { #pragma warning disable IDE0059 // Unnecessary assignment of a value var ignored = task.Exception; #pragma warning restore IDE0059 // Unnecessary assignment of a value } else { task.ContinueWith( IgnoreTaskContinuation, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } public static async Task WithCancellation(this Task task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using (cancellationToken.Register(state => { ((TaskCompletionSource)state!).TrySetResult(null!); }, tcs)) { var resultTask = await Task.WhenAny(task, tcs.Task); if (resultTask == tcs.Task) { throw new OperationCanceledException(cancellationToken); } return await task; } } } }