/// <summary> /// Gets a multicast instance or creates a new one. /// </summary> /// <param name="vmType">View model type helper.</param> /// <param name="vmInstanceId">Optional view model instance identifier.</param> /// <returns>View model instance.</returns> private BaseVM GetMulticastInstance(TypeHelper vmType, string vmInstanceId) { string key = vmType.FullName; MulticastVM vm = null; lock (_keyBasedLock.GetOrAdd(key, _ => new object())) { if (!_memoryCache.TryGetValue(key, out HashSet <MulticastVM> vmCollections)) { vm = CreateMulticastInstance(vmType, vmInstanceId, key); vmCollections = new HashSet <MulticastVM> { vm }; _memoryCache.Set(key, vmCollections); } else { vm = vmCollections.FirstOrDefault(x => x.IsMember); if (vm != null) { vm.AddRef(); } else { vm = CreateMulticastInstance(vmType, vmInstanceId, key); vmCollections.Add(vm); } } } return(vm); }
/// <summary> /// Removes multicast view model instance from the cache. /// </summary> /// <param name="vm">Multicast view model.</param> /// <param name="key">Key to the cache collection, which is the view model's type name.</param> private void RemoveMulticastInstance(MulticastVM vm, string key) { lock (_keyBasedLock.GetOrAdd(key, _ => new object())) { if (_memoryCache.TryGetValue(key, out HashSet <MulticastVM> vmCollections)) { vmCollections.Remove(vm); } } }