mirror of
https://github.com/ElectronNET/Electron.NET.git
synced 2026-02-11 21:23:48 +00:00
47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ElectronNET.API
|
|
{
|
|
internal static class AsyncHelper
|
|
{
|
|
private static readonly TaskFactory _taskFactory = new
|
|
TaskFactory(CancellationToken.None,
|
|
TaskCreationOptions.None,
|
|
TaskContinuationOptions.None,
|
|
TaskScheduler.Default);
|
|
|
|
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
|
|
=> _taskFactory
|
|
.StartNew(func)
|
|
.Unwrap()
|
|
.GetAwaiter()
|
|
.GetResult();
|
|
|
|
public static void RunSync(Func<Task> func)
|
|
=> _taskFactory
|
|
.StartNew(func)
|
|
.Unwrap()
|
|
.GetAwaiter()
|
|
.GetResult();
|
|
|
|
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout)
|
|
{
|
|
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
|
|
{
|
|
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
|
|
if (completedTask == task)
|
|
{
|
|
timeoutCancellationTokenSource.Cancel();
|
|
return await task; // Very important in order to propagate exceptions
|
|
}
|
|
else
|
|
{
|
|
throw new TimeoutException($"{nameof(TimeoutAfter)}: The operation has timed out after {timeout:mm\\:ss}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|