From e1e4759c5730bab2eeb9b67800c0e4ffc536cb6a Mon Sep 17 00:00:00 2001 From: Casper-NS Date: Tue, 19 Dec 2023 14:02:41 +0100 Subject: [PATCH] fixed a bug where multiple threads tried accessing the db context --- CentralHub.Api/Services/LocalizationService.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/CentralHub.Api/Services/LocalizationService.cs b/CentralHub.Api/Services/LocalizationService.cs index 06beea5..e92ea76 100644 --- a/CentralHub.Api/Services/LocalizationService.cs +++ b/CentralHub.Api/Services/LocalizationService.cs @@ -44,6 +44,8 @@ public async Task AggregateMeasurementsAsync(CancellationToken stoppingToken) var roomMeasurementGroups = await aggregatorRepository.GetRoomMeasurementGroupsAsync(stoppingToken); var allRooms = await roomRepository.GetRoomsAsync(stoppingToken); using var measuredRoomsMutex = new CancellableMutex>(new List()); + using var aggregatedMeasurementsMutex = new CancellableMutex>(new List()); + await Parallel.ForEachAsync( roomMeasurementGroups, @@ -60,9 +62,8 @@ await Parallel.ForEachAsync( await measuredRoomsMutex.Lock(m => m.Add(room), cancellationToken); - await aggregatorRepository.AddAggregatedMeasurementAsync( - CreateAggregatedMeasurement(room, roomMeasurementGroup.Value), - cancellationToken); + var aggregatedMeasurement = CreateAggregatedMeasurement(room, roomMeasurementGroup.Value); + await aggregatedMeasurementsMutex.Lock(am => am.Add(aggregatedMeasurement), cancellationToken); }); await measuredRoomsMutex.Lock(async m => @@ -75,6 +76,17 @@ await aggregatorRepository.AddAggregatedMeasurementAsync( } }, stoppingToken); + + await aggregatedMeasurementsMutex.Lock(async am => + { + foreach (var aggregatedMeasurement in am) + { + await aggregatorRepository.AddAggregatedMeasurementAsync( + aggregatedMeasurement, + stoppingToken); + } + }, + stoppingToken); } private static AggregatedMeasurementDto CreateAggregatedMeasurement(RoomDto room, IReadOnlyCollection measurementGroups)