feat: Parallel loops for initialization

This commit is contained in:
Timothy Schenk 2024-02-05 16:18:47 +01:00
parent 0d0b27ba49
commit 0c2accd72c
Signed by: rainote
SSH key fingerprint: SHA256:pnkNSDwpAnaip00xaZlVFHKKsS7T8UtOomMzvs0yITE

View file

@ -4,7 +4,6 @@ using System.Collections.Concurrent;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Reflection; using System.Reflection;
using System.Threading.Channels; using System.Threading.Channels;
using DotNext.Collections.Generic;
using DotNext.Linq.Expressions; using DotNext.Linq.Expressions;
using DotNext.Metaprogramming; using DotNext.Metaprogramming;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -47,16 +46,16 @@ public class PacketDistributor<TPacketIdEnum, TSession> where TPacketIdEnum : En
} }
var tempDeserializationMap = var tempDeserializationMap =
new Dictionary<TPacketIdEnum, Func<byte[], IIncomingPacket>>(); new ConcurrentDictionary<TPacketIdEnum, Func<byte[], IIncomingPacket>>();
_packetHandlersInstantiation = new ConcurrentDictionary<TPacketIdEnum, IPacketHandler<TSession>?>(); _packetHandlersInstantiation = new ConcurrentDictionary<TPacketIdEnum, IPacketHandler<TSession>?>();
packetHandlers.ForEach(x => Parallel.ForEach(packetHandlers, packetHandlerPair =>
{ {
var packetHandler = var packetHandler =
ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider,
x.Value); packetHandlerPair.Value);
_packetHandlersInstantiation.TryAdd(x.Key, packetHandler as IPacketHandler<TSession>); _packetHandlersInstantiation.TryAdd(packetHandlerPair.Key, packetHandler as IPacketHandler<TSession>);
}); });
foreach (var packetsType in packetDictionary) Parallel.ForEach(packetDictionary, packetsType =>
{ {
var lambda = CodeGenerator.Lambda<Func<byte[], IIncomingPacket>>(fun => var lambda = CodeGenerator.Lambda<Func<byte[], IIncomingPacket>>(fun =>
{ {
@ -69,8 +68,8 @@ public class PacketDistributor<TPacketIdEnum, TSession> where TPacketIdEnum : En
CodeGenerator.Return(packetVariable); CodeGenerator.Return(packetVariable);
}).Compile(); }).Compile();
tempDeserializationMap.Add(packetsType.Key, lambda); tempDeserializationMap.TryAdd(packetsType.Key, lambda);
} });
_deserializationMap = tempDeserializationMap.ToImmutableDictionary(); _deserializationMap = tempDeserializationMap.ToImmutableDictionary();
} }