Skip to content

Instantly share code, notes, and snippets.

@davidvesely
Created March 22, 2022 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidvesely/42b57639d121b3a48a65540574248f8f to your computer and use it in GitHub Desktop.
Save davidvesely/42b57639d121b3a48a65540574248f8f to your computer and use it in GitHub Desktop.
Execute async as sync operation
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