Skip to content

Commit 955b746

Browse files
committed
Use a concurrent dictionary for cachedTriggerContextFactories
1 parent 7ad25f8 commit 955b746

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

src/EntityFrameworkCore.Triggered/Internal/TriggerContextDescriptor.cs

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
using System;
2+
using System.Buffers;
3+
using System.Collections.Concurrent;
24
using System.Collections.Generic;
35
using Microsoft.EntityFrameworkCore.ChangeTracking;
46

57
namespace EntityFrameworkCore.Triggered.Internal
68
{
79
public readonly struct TriggerContextDescriptor
810
{
9-
[ThreadStatic]
10-
static Dictionary<Type, Func<object, PropertyValues?, ChangeType, object>>? _cachedTriggerContextFactories;
11+
static readonly ConcurrentDictionary<Type, Func<object, PropertyValues?, ChangeType, object>> _cachedTriggerContextFactories = new();
1112

1213
readonly EntityEntry _entityEntry;
1314
readonly ChangeType _changeType;
@@ -37,19 +38,10 @@ public object GetTriggerContext()
3738

3839
var entityType = entityEntry.Entity.GetType();
3940

40-
if (_cachedTriggerContextFactories == null)
41-
{
42-
_cachedTriggerContextFactories = new Dictionary<Type, Func<object, PropertyValues?, ChangeType, object>>();
43-
}
44-
45-
if (!_cachedTriggerContextFactories.TryGetValue(entityType, out var triggerContextFactory))
46-
{
47-
triggerContextFactory = (Func<object, PropertyValues?, ChangeType, object>)typeof(TriggerContextFactory<>).MakeGenericType(entityType)
41+
var triggerContextFactory = _cachedTriggerContextFactories.GetOrAdd(entityType, entityType =>
42+
(Func<object, PropertyValues?, ChangeType, object>)typeof(TriggerContextFactory<>).MakeGenericType(entityType)
4843
.GetMethod(nameof(TriggerContextFactory<object>.Activate))
49-
.CreateDelegate(typeof(Func<object, PropertyValues?, ChangeType, object>));
50-
51-
_cachedTriggerContextFactories.Add(entityType, triggerContextFactory);
52-
}
44+
.CreateDelegate(typeof(Func<object, PropertyValues?, ChangeType, object>)));
5345

5446
return triggerContextFactory(entityEntry.Entity, originalValues, changeType);
5547
}

0 commit comments

Comments
 (0)