CodeLiturgy.Dashboard/BlueWest/Core/System/ThreadServer.cs

84 lines
2.2 KiB
C#

using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using BlueWest.Core.ComponentSystem;
using BlueWest.Tools;
namespace BlueWest.Core
{
public sealed class ThreadServer
{
public bool IsActive { get; private set; }
public EventManager EventManager => _eventManager;
private readonly EventManager _eventManager;
public ThreadServer(EventManager eventManager)
{
_eventManager = eventManager;
}
public void Init()
{
InstantiateControllers();
IsActive = true;
}
/*public static readonly Expression<Entity, EntityDto> MappingExpression = x => new EntityDto
{
Name = x.Name,
...
};*/
private static Type[]? GetTypesFromBehaviors()
{
return Assembly.GetAssembly(typeof(Artefact))
?.GetTypes()
.Where(aType => aType.IsClass
&& !aType.IsAbstract
&& aType.IsSubclassOf(typeof(Artefact)))
.ToArray();
}
private void InstantiateControllers()
{
var types = GetTypesFromBehaviors();
if (types == null)
{
return;
}
foreach (var t in types)
{
InstantiateBehavior(t);
}
}
private void InstantiateBehavior(Type type)
{
SpawnThread(() =>
{
#pragma warning disable CS8600
object instantiate = Activator.CreateInstance(type);
#pragma warning restore CS8600
#pragma warning disable CS8600
Artefact behavior = instantiate as Artefact;
#pragma warning restore CS8600
#pragma warning disable CS8602
behavior.SetupEntity(_eventManager);
#pragma warning restore CS8602
behavior.RunLoop();
});
}
public void SpawnThread( Action action, ThreadPriority threadPriority = ThreadPriority.BelowNormal)
{
var thread = new Thread(action.Invoke)
{
Priority = threadPriority
};
thread.Start();
}
}
}