This repository has been archived by the owner on Apr 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7d7381c
commit 1d76124
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
using System; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace Atles.Core.Utilities | ||
{ | ||
/// <summary> | ||
/// Helper class to run async methods within a sync process. | ||
/// https://www.ryadel.com/en/asyncutil-c-helper-class-async-method-sync-result-wait/ | ||
/// </summary> | ||
public static class AsyncUtil | ||
{ | ||
private static readonly TaskFactory TaskFactory = new | ||
TaskFactory(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(); | ||
} | ||
} |