mirror of
https://github.com/ElectronNET/Electron.NET.git
synced 2026-02-14 13:44:47 +00:00
Aanpassingen autoupdate & async code
This commit is contained in:
46
ElectronNET.API/AsyncHelper.cs
Normal file
46
ElectronNET.API/AsyncHelper.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user