From ed6b411086c8727d439c76c9ba4146e717a7c23c Mon Sep 17 00:00:00 2001 From: Mauro Servienti Date: Sun, 13 Dec 2020 15:32:45 +0100 Subject: [PATCH] Use ConcurrentDictionary to track properties and events subscriptions (#196) --- src/ServiceComposer.AspNetCore/DynamicViewModel.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/ServiceComposer.AspNetCore/DynamicViewModel.cs b/src/ServiceComposer.AspNetCore/DynamicViewModel.cs index cc01327f..a27748c0 100644 --- a/src/ServiceComposer.AspNetCore/DynamicViewModel.cs +++ b/src/ServiceComposer.AspNetCore/DynamicViewModel.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.Linq; @@ -13,9 +14,9 @@ class DynamicViewModel : DynamicObject, IPublishCompositionEvents, ICompositionE readonly string _requestId; readonly RouteData _routeData; readonly HttpRequest _httpRequest; - readonly IDictionary>> _subscriptions = new Dictionary>>(); - readonly IDictionary>> _compositionEventsSubscriptions = new Dictionary>>(); - readonly IDictionary _properties = new Dictionary(); + readonly ConcurrentDictionary>> _subscriptions = new ConcurrentDictionary>>(); + readonly ConcurrentDictionary>> _compositionEventsSubscriptions = new ConcurrentDictionary>>(); + readonly ConcurrentDictionary _properties = new ConcurrentDictionary(); public DynamicViewModel(string requestId, RouteData routeData, HttpRequest httpRequest) { @@ -31,7 +32,7 @@ public void Subscribe(EventHandler handler) if (!_subscriptions.TryGetValue(typeof(TEvent), out var handlers)) { handlers = new List>(); - _subscriptions.Add(typeof(TEvent), handlers); + _subscriptions.TryAdd(typeof(TEvent), handlers); } handlers.Add((requestId, pageViewModel, @event, routeData, query) => handler(requestId, pageViewModel, (TEvent) @event, routeData, query)); @@ -42,7 +43,7 @@ public void Subscribe(CompositionEventHandler handler) if (!_compositionEventsSubscriptions.TryGetValue(typeof(TEvent), out var handlers)) { handlers = new List>(); - _compositionEventsSubscriptions.Add(typeof(TEvent), handlers); + _compositionEventsSubscriptions.TryAdd(typeof(TEvent), handlers); } handlers.Add((@event, request) => handler((TEvent) @event, request)); @@ -52,7 +53,7 @@ public void Subscribe(CompositionEventHandler handler) public override bool TrySetMember(SetMemberBinder binder, object value) { - _properties[binder.Name] = value; + _properties.AddOrUpdate(binder.Name, value, (key, existingValue) => value); return true; }