| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | |
| | | 9 | | namespace dotnet_etcd.helper; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Helps with running async code in sync methods |
| | | 13 | | /// </summary> |
| | | 14 | | /// <remarks> |
| | | 15 | | /// Based on the AsyncHelper of the Microsoft.AspNet.Identity project |
| | | 16 | | /// (https://web.archive.org/web/20200411071640/https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.A |
| | | 17 | | /// </remarks> |
| | | 18 | | public static class AsyncHelper |
| | | 19 | | { |
| | 0 | 20 | | private static readonly TaskFactory MyTaskFactory = new(CancellationToken.None, |
| | 0 | 21 | | TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Runs the provided async function provided in <paramref name="func" /> in a synchronous way |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="func">A call to the async method</param> |
| | | 27 | | /// <example> |
| | | 28 | | /// <code> |
| | | 29 | | /// AsyncHelper.RunSync(SomeFunctionAsync) |
| | | 30 | | /// </code> |
| | | 31 | | /// or |
| | | 32 | | /// <code> |
| | | 33 | | /// AsyncHelper.RunSync(async () => await SomeFunctionAsync()) |
| | | 34 | | /// </code> |
| | | 35 | | /// </example> |
| | | 36 | | public static void RunSync(Func<Task> func) |
| | 0 | 37 | | { |
| | 0 | 38 | | CultureInfo cultureUi = CultureInfo.CurrentUICulture; |
| | 0 | 39 | | CultureInfo culture = CultureInfo.CurrentCulture; |
| | 0 | 40 | | MyTaskFactory.StartNew(() => |
| | 0 | 41 | | { |
| | 0 | 42 | | Thread.CurrentThread.CurrentCulture = culture; |
| | 0 | 43 | | Thread.CurrentThread.CurrentUICulture = cultureUi; |
| | 0 | 44 | | return func(); |
| | 0 | 45 | | }).Unwrap().GetAwaiter().GetResult(); |
| | 0 | 46 | | } |
| | | 47 | | } |