using System; using System.Threading; using System.Threading.Tasks; namespace Kreta.Core { //https://cpratt.co/async-tips-tricks/ //https://www.ryadel.com/en/asyncutil-c-helper-class-async-method-sync-result-wait/ /// /// Helper class to run async methods within a sync process. /// public static class AsyncUtil { private static readonly TaskFactory _taskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); /// /// Executes an async Task method which has a void return value synchronously /// USAGE: AsyncUtil.RunSync(() => AsyncMethod()); /// /// Task method to execute public static void RunSync(Func task) => _taskFactory .StartNew(task) .Unwrap() .GetAwaiter() .GetResult(); /// /// Executes an async Task method which has a T return type synchronously /// USAGE: T result = AsyncUtil.RunSync(() => AsyncMethod()); /// /// Return Type /// Task method to execute /// public static TResult RunSync(Func> task) => _taskFactory .StartNew(task) .Unwrap() .GetAwaiter() .GetResult(); } }