1
+ using System ;
2
+ using System . Collections . Concurrent ;
3
+ using System . Linq ;
4
+ using System . Threading . Tasks ;
5
+ using GoDough . Runtime . LivecycleHooks ;
6
+
7
+ namespace GoDough . Threading {
8
+ public class Dispatcher : IOnProcess {
9
+ private class ActionOrFunc {
10
+ public Action Action { get ; set ; }
11
+ public Func < object > Func { get ; set ; }
12
+ public TaskCompletionSource < object > Completion { get ; set ; }
13
+ }
14
+
15
+ private ConcurrentDictionary < string , ActionOrFunc > _actions = new ConcurrentDictionary < string , ActionOrFunc > ( ) ;
16
+
17
+ public void Invoke ( Action action ) {
18
+ this . _actions [ Guid . NewGuid ( ) . ToString ( ) ] = new ActionOrFunc {
19
+ Action = action
20
+ } ;
21
+ }
22
+
23
+ public Task < T > Invoke < T > ( Func < T > func ) where T : class {
24
+ var completionSource = new TaskCompletionSource < object > ( ) ;
25
+ this . _actions [ Guid . NewGuid ( ) . ToString ( ) ] = new ActionOrFunc {
26
+ Func = func as Func < object > ,
27
+ Completion = completionSource
28
+ } ;
29
+
30
+ return completionSource . Task . ContinueWith < T > ( ( Task < object > t ) => {
31
+ return t . Result as T ;
32
+ } ) ;
33
+ }
34
+
35
+ public void OnProcess ( double delta ) {
36
+ while ( this . _actions . Count > 0 ) {
37
+ var action = this . _actions . FirstOrDefault ( ) ;
38
+
39
+ this . _actions . TryRemove ( action ) ;
40
+
41
+ if ( action . Value . Action != null ) {
42
+ action . Value . Action ( ) ;
43
+ } else {
44
+ var result = action . Value . Func ( ) ;
45
+ action . Value . Completion . SetResult ( result ) ;
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }
0 commit comments