This repository was archived by the owner on Apr 14, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments