Skip to content
This repository was archived by the owner on Apr 14, 2023. It is now read-only.

Commit 1d76124

Browse files
committed
Add AsyncUtil.cs
1 parent 7d7381c commit 1d76124

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/Atles.Core/Utilities/AsyncUtil.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using System;
2+
using System.Threading;
3+
using System.Threading.Tasks;
4+
5+
namespace Atles.Core.Utilities
6+
{
7+
/// <summary>
8+
/// Helper class to run async methods within a sync process.
9+
/// https://www.ryadel.com/en/asyncutil-c-helper-class-async-method-sync-result-wait/
10+
/// </summary>
11+
public static class AsyncUtil
12+
{
13+
private static readonly TaskFactory TaskFactory = new
14+
TaskFactory(CancellationToken.None,
15+
TaskCreationOptions.None,
16+
TaskContinuationOptions.None,
17+
TaskScheduler.Default);
18+
19+
/// <summary>
20+
/// Executes an async Task method which has a void return value synchronously
21+
/// USAGE: AsyncUtil.RunSync(() => AsyncMethod());
22+
/// </summary>
23+
/// <param name="task">Task method to execute</param>
24+
public static void RunSync(Func<Task> task)
25+
=> TaskFactory
26+
.StartNew(task)
27+
.Unwrap()
28+
.GetAwaiter()
29+
.GetResult();
30+
31+
/// <summary>
32+
/// Executes an async Task<T> method which has a T return type synchronously
33+
/// USAGE: T result = AsyncUtil.RunSync(() => AsyncMethod<T>());
34+
/// </summary>
35+
/// <typeparam name="TResult">Return Type</typeparam>
36+
/// <param name="task">Task<T> method to execute</param>
37+
/// <returns></returns>
38+
public static TResult RunSync<TResult>(Func<Task<TResult>> task)
39+
=> TaskFactory
40+
.StartNew(task)
41+
.Unwrap()
42+
.GetAwaiter()
43+
.GetResult();
44+
}
45+
}

0 commit comments

Comments
 (0)