Created
March 22, 2022 13:07
-
-
Save davidvesely/42b57639d121b3a48a65540574248f8f to your computer and use it in GitHub Desktop.
Execute async as sync operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Kongsberg.KSim.Extensions.Gmdss.Domain | |
{ | |
/// <summary> | |
/// Helper class to run async methods within a sync process. | |
/// </summary> | |
public static class AsyncUtil | |
{ | |
private static readonly TaskFactory TaskFactory = new( | |
CancellationToken.None, | |
TaskCreationOptions.None, | |
TaskContinuationOptions.None, | |
TaskScheduler.Default); | |
/// <summary> | |
/// Executes an async Task method which has a void return value synchronously | |
/// USAGE: AsyncUtil.RunSync(() => AsyncMethod()); | |
/// </summary> | |
/// <param name="task">Task method to execute</param> | |
public static void RunSync(Func<Task> task) | |
=> TaskFactory | |
.StartNew(task) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
/// <summary> | |
/// Executes an async Task<T> method which has a T return type synchronously | |
/// USAGE: T result = AsyncUtil.RunSync(() => AsyncMethod<T>()); | |
/// </summary> | |
/// <typeparam name="TResult">Return Type</typeparam> | |
/// <param name="task">Task<T> method to execute</param> | |
/// <returns></returns> | |
public static TResult RunSync<TResult>(Func<Task<TResult>> task) | |
=> TaskFactory | |
.StartNew(task) | |
.Unwrap() | |
.GetAwaiter() | |
.GetResult(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment