mirror of https://github.com/Squidex/squidex.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
2.0 KiB
57 lines
2.0 KiB
// ==========================================================================
|
|
// 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<Task> 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<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
|
|
{
|
|
var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
using (cancellationToken.Register(state =>
|
|
{
|
|
((TaskCompletionSource<object>)state!).TrySetResult(null!);
|
|
},
|
|
tcs))
|
|
{
|
|
var resultTask = await Task.WhenAny(task, tcs.Task);
|
|
if (resultTask == tcs.Task)
|
|
{
|
|
throw new OperationCanceledException(cancellationToken);
|
|
}
|
|
|
|
return await task;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|