Skip to content

Commit 3081e44

Browse files
author
Marco Klein
committed
feat: ✨ Add Dispatcher
1 parent 2c9338c commit 3081e44

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Source/Threading/Dispatcher.cs

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using GoDough.Composition.Extensions;
2+
using GoDough.Runtime.LivecycleHooks;
3+
using Microsoft.Extensions.DependencyInjection;
4+
5+
namespace GoDough.Threading {
6+
public static class IServiceCollectionExtensions {
7+
public static IServiceCollection AddThreadingUtilities(this IServiceCollection serviceCollection) {
8+
return serviceCollection
9+
.AddSingleton<Dispatcher>()
10+
.MapSingleton<IOnProcess, Dispatcher>();
11+
}
12+
}
13+
}

0 commit comments

Comments
 (0)