Skip to content

Commit

Permalink
fixed a bug where multiple threads tried accessing the db context
Browse files Browse the repository at this point in the history
  • Loading branch information
Casper-NS committed Dec 19, 2023
1 parent 8d1420e commit e1e4759
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions CentralHub.Api/Services/LocalizationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<List<RoomDto>>(new List<RoomDto>());
using var aggregatedMeasurementsMutex = new CancellableMutex<List<AggregatedMeasurementDto>>(new List<AggregatedMeasurementDto>());


await Parallel.ForEachAsync(
roomMeasurementGroups,
Expand All @@ -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 =>
Expand All @@ -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<MeasurementGroup> measurementGroups)
Expand Down

0 comments on commit e1e4759

Please sign in to comment.