System.Threading.ReaderWriterLockSlim.EnterWriteLock()

Here are the examples of the csharp api System.Threading.ReaderWriterLockSlim.EnterWriteLock() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

944 Examples 7

19 Source : ControlCollection.cs
with MIT License
from blish-hud

public void AddRange(IEnumerable<T> items) {
            _listLock.EnterWriteLock();
            _innerList.AddRange(items);
            this.IsEmpty = !_innerList.Any();
            _listLock.ExitWriteLock();
        }

19 Source : ControlCollection.cs
with MIT License
from blish-hud

public void Clear() {
            T[] oldItems = this.ToArray();

            _listLock.EnterWriteLock();
            _innerList.Clear();
            this.IsEmpty = true;
            _listLock.ExitWriteLock();
            
            foreach (var item in oldItems) {
                item.Parent = null;
            }
        }

19 Source : ControlCollection.cs
with MIT License
from blish-hud

public bool Remove(T item) {
            _listLock.EnterWriteLock();

            try {
                return _innerList.Remove(item);
            } finally {
                this.IsEmpty = !_innerList.Any();
                _listLock.ExitWriteLock();
            }
        }

19 Source : ControlCollection.cs
with MIT License
from blish-hud

public void Insert(int index, T item) {
            _listLock.EnterWriteLock();
            _innerList.Insert(index, item);
            _listLock.ExitWriteLock();
        }

19 Source : ControlCollection.cs
with MIT License
from blish-hud

public void RemoveAt(int index) {
            _listLock.EnterWriteLock();
            _innerList.RemoveAt(index);
            _listLock.ExitWriteLock();
        }

19 Source : KeyboardHandler.cs
with MIT License
from blish-hud

internal void StageKeyBinding(KeyBinding keyBinding) {
            _stagedKeyBindingLock.EnterWriteLock();
            if (!_stagedKeyBindings.Contains(keyBinding)) {
                Logger.Debug("Staging keybind {keybind}.", keyBinding.GetBindingDisplayText());
                _stagedKeyBindings.Add(keyBinding);
            }
            _stagedKeyBindingLock.ExitWriteLock();
        }

19 Source : KeyboardHandler.cs
with MIT License
from blish-hud

internal void UnstageKeyBinding(KeyBinding keyBinding) {
            _stagedKeyBindingLock.EnterWriteLock();
            if (_stagedKeyBindings.Contains(keyBinding)) {
                Logger.Debug("Unstaging keybind {keybind}.", keyBinding.GetBindingDisplayText());
                _stagedKeyBindings.Remove(keyBinding);
            }
            _stagedKeyBindingLock.ExitWriteLock();
        }

19 Source : SettingCollection.cs
with MIT License
from blish-hud

public SettingEntry<TEntry> DefineSetting<TEntry>(string entryKey, TEntry defaultValue, Func<string> displayNameFunc = null, Func<string> descriptionFunc = null) {
            // We don't need to check if we've loaded because the first check uses this[key] which
            // will load if we haven't already since it references this.Entries instead of _entries
            if (!(this[entryKey] is SettingEntry<TEntry> definedEntry)) {
                definedEntry = SettingEntry<TEntry>.InitSetting(entryKey, defaultValue);
            }

            definedEntry.GetDisplayNameFunc = displayNameFunc ?? (() => null);
            definedEntry.GetDescriptionFunc = descriptionFunc ?? (() => null);
            definedEntry.SessionDefined     = true;

            _entryLock.EnterWriteLock();
            _undefinedEntries.Remove(definedEntry);
            _definedEntries.Add(definedEntry);
            _entryLock.ExitWriteLock();

            return definedEntry;
        }

19 Source : SettingCollection.cs
with MIT License
from blish-hud

public void UndefineSetting(string entryKey) {
            var entryToRemove = this[entryKey];

            if (entryToRemove != null) {
                _entryLock.EnterWriteLock();
                _undefinedEntries.Remove(entryToRemove);
                _definedEntries.Remove(entryToRemove);
                _entryLock.ExitWriteLock();
            }
        }

19 Source : SettingCollection.cs
with MIT License
from blish-hud

private void Load() {
            if (_entryTokens == null) return;

            _entryLock.EnterWriteLock();
            _undefinedEntries = JsonConvert.DeserializeObject<List<SettingEntry>>(_entryTokens.ToString(), GameService.Settings.JsonReaderSettings).Where((se) => se != null).ToList();
            _entryLock.ExitWriteLock();

            _entryTokens = null;
        }

19 Source : TEStorageHeart.cs
with MIT License
from blushiemagic

public void EnterWriteLock()
        {
            itemsLock.EnterWriteLock();
        }

19 Source : Topic.cs
with GNU General Public License v3.0
from bonarr

public void AddSubscription(ISubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException("subscription");
            }

            try
            {
                SubscriptionLock.EnterWriteLock();

                MarkUsed();

                Subscriptions.Add(subscription);
                
                // Created -> Hreplacedubscriptions
                Interlocked.CompareExchange(ref State,
                                            TopicState.Hreplacedubscriptions,
                                            TopicState.NoSubscriptions);
            }
            finally
            {
                SubscriptionLock.ExitWriteLock();
            }
        }

19 Source : Topic.cs
with GNU General Public License v3.0
from bonarr

public void RemoveSubscription(ISubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException("subscription");
            }

            try
            {
                SubscriptionLock.EnterWriteLock();

                MarkUsed();
              
                Subscriptions.Remove(subscription);
               

                if (Subscriptions.Count == 0)
                {
                    // Hreplacedubscriptions -> NoSubscriptions
                    Interlocked.CompareExchange(ref State,
                                                TopicState.NoSubscriptions,
                                                TopicState.Hreplacedubscriptions);
                }
            }
            finally
            {
                SubscriptionLock.ExitWriteLock();
            }
        }

19 Source : MostlyReadDictionary.cs
with Apache License 2.0
from busterwood

public TValue GetOrAdd(TKey key, Func<TKey, TValue> addFunc)
        {
            Contract.RequiresNotNull(addFunc, nameof(addFunc));

            // simple case of we already have a value for the key
            _rwLock.EnterReadLock();
            try
            {
                if (_map.TryGetValue(key, out var value)) return value;
            }
            finally
            {
                _rwLock.ExitReadLock();
            }

            // no value for the key
            _rwLock.EnterUpgradeableReadLock();
            try
            {
                // some other thread may have just added it
                if (_map.TryGetValue(key, out var value)) return value;

                // the function may take "some time" so evaluate it outside of the write lock so other threads can still read the dictionary
                value = addFunc(key);

                _rwLock.EnterWriteLock();
                try
                {
                    _map[key] = value;
                }
                finally
                {
                    _rwLock.ExitWriteLock();
                }
                return value;
            }
            finally
            {
                _rwLock.ExitUpgradeableReadLock();
            }
        }

19 Source : FrameworkContainer.cs
with MIT License
from CalciumFramework

public void Register<TInterface>(TInterface instance, string key = null)
		{
			key = GetKeyValueOrDefault(key);
			Type type = typeof(TInterface);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(type, 
						out ResolverDictionary value))
				{
					value = new ResolverDictionary();
				}

				value[key] = new Resolver { CreateInstanceFunc = () => instance };
				typeDictionary[type] = value;
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : FrameworkContainer.cs
with MIT License
from CalciumFramework

public void Register<T>(
			Func<T> getInstanceFunc, 
			bool singleton = false, 
			string key = null)
		{
			replacedertArg.IsNotNull(getInstanceFunc, nameof(getInstanceFunc));

			key = GetKeyValueOrDefault(key);
			Type type = typeof(T);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(type, 
					out ResolverDictionary resolverDictionary))
				{
					resolverDictionary = new ResolverDictionary();
				}

				Resolver resolver = new Resolver { Singleton = singleton };

				Func<object> getObjectFunc = () =>
				{
					if (cycleDictionary.TryGetValue(type, out List<string> keys))
					{
						if (keys.Contains(key))
						{
							/* TODO: Rather than throwing an exception, 
							 * we could Post the property set operation to the UI thread. */
							throw new ResolutionException(
								$"Cycle detected for {type} with key \"{key}\"");
						}

						keys.Add(key);
					}
					else
					{
						keys = new List<string> { key };
						cycleDictionary.Add(type, keys);
					}

					T result;
					try
					{
						result = getInstanceFunc();
					}
					finally
					{
						keys.Remove(key);
						if (!keys.Any())
						{
							cycleDictionary.Remove(type);
						}
					}

					if (resolver.Singleton)
					{
						resolver.CreateInstanceFunc = null;
						resolver.Instance = result;
					}

					return result;
				};

				resolver.CreateInstanceFunc = getObjectFunc;
				
				resolverDictionary[key] = resolver;
				keyDictionary[key] = type;

				typeDictionary[type] = resolverDictionary;
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : FrameworkContainer.cs
with MIT License
from CalciumFramework

public void Register(
			Type type, 
			Func<object> getInstanceFunc, 
			bool singleton = false, 
			string key = null)
		{
			replacedertArg.IsNotNull(type, nameof(type));
			replacedertArg.IsNotNull(getInstanceFunc, nameof(getInstanceFunc));

			key = GetKeyValueOrDefault(key);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(type, 
						out ResolverDictionary resolverDictionary))
				{
					resolverDictionary = new ResolverDictionary();
				}

				Resolver resolver = new Resolver { Singleton = singleton };

				Func<object> getObjectFunc = () =>
				{
					var result = getInstanceFunc();

					if (resolver.Singleton)
					{
						resolver.CreateInstanceFunc = null;
						resolver.Instance = result;
					}

					return result;
				};

				resolver.CreateInstanceFunc = getObjectFunc;
				
				resolverDictionary[key] = resolver;
				keyDictionary[key] = type;

				typeDictionary[type] = resolverDictionary;
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : FrameworkContainer.cs
with MIT License
from CalciumFramework

public void Register(Type type, object instance, string key = null)
		{
			replacedertArg.IsNotNull(type, nameof(type));

			key = GetKeyValueOrDefault(key);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(
						type, out ResolverDictionary value))
				{
					value = new ResolverDictionary();
				}

				Resolver info = new Resolver { CreateInstanceFunc = () => instance };

				value[key] = info;

				typeDictionary[type] = value;
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : FrameworkContainer.cs
with MIT License
from CalciumFramework

object Instantiate(Type type)
		{
			ConstructorInvokeInfo invokeInfo;

			bool useLock = ThreadSafe;
			if (useLock)
			{
				constructorDictionaryLockSlim.EnterReadLock();
			}

			try
			{
				if (constructorDictionary.TryGetValue(type, out invokeInfo))
				{
					return Instantiate(invokeInfo);
				}
			}
			finally
			{
				if (useLock)
				{
					constructorDictionaryLockSlim.ExitReadLock();
				}
			}

#if NETFX_CORE
			var constructors = type.GetTypeInfo().DeclaredConstructors.Where(x => !x.IsStatic && x.IsPublic).ToArray();
#else
			var constructors = type.GetTypeInfo().DeclaredConstructors;
#endif

			ConstructorInfo constructor = null;

			if (constructors.Any())
			{
				ConstructorInfo bestMatch = null;
				int biggestLength = -1;

				foreach (ConstructorInfo constructorInfo in constructors)
				{
					var dependencyAttributes = constructorInfo.GetCustomAttributes(typeof(InjectDependenciesAttribute), false).ToList();
					//#if NETSTANDARD || NETFX_CORE
					//					/* Unfortunately LINQ .Count() is much slower than .Length */
					//					var attributeCount = dependencyAttributes.Count();
					//#else
					//					var attributeCount = dependencyAttributes.Length;
					//#endif
					var attributeCount = dependencyAttributes.Count;
					bool hasAttribute = attributeCount > 0;

					if (hasAttribute)
					{
						constructor = constructorInfo;
						break;
					}

					var length = constructorInfo.GetParameters().Length;

					if (length > biggestLength)
					{
						biggestLength = length;
						bestMatch = constructorInfo;
					}
				}

				if (constructor == null)
				{
					constructor = bestMatch;
				}
			}
			else
			{
				ConstructorInfo bestMatch = null;
				int biggestLength = -1;

				constructors = type.GetTypeInfo().DeclaredConstructors.Where(x => !x.IsStatic && x.IsPrivate);

				foreach (ConstructorInfo constructorInfo in constructors)
				{
					var attributes = constructorInfo.GetCustomAttributes(typeof(InjectDependenciesAttribute), false);

					if (attributes.Any())
					{
						constructor = constructorInfo;
						break;
					}

					var length = constructorInfo.GetParameters().Length;

					if (length > biggestLength)
					{
						biggestLength = length;
						bestMatch = constructorInfo;
					}
				}

				if (constructor == null)
				{
					constructor = bestMatch;
				}
			}

			if (constructor == null)
			{
				throw new ResolutionException(
					"Could not locate a constructor for " + type.FullName);
			}

			invokeInfo = new ConstructorInvokeInfo(constructor);

			if (useLock)
			{
				constructorDictionaryLockSlim.EnterWriteLock();
			}

			try
			{
				if (cacheEnabled)
				{
					constructorDictionary[type] = invokeInfo;
				}
			}
			finally
			{
				if (useLock)
				{
					constructorDictionaryLockSlim.ExitWriteLock();
				}
			}

			return Instantiate(invokeInfo);
		}

19 Source : WeakReferencingContainer.cs
with MIT License
from CalciumFramework

public void Register(Type fromType, Type toType,
			bool singleton = false, string key = null)
		{
			key = GetKeyValueOrDefault(key);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(fromType,
						out ResolverDictionary resolverDictionary))
				{
					resolverDictionary = new ResolverDictionary();
					typeDictionary.Add(fromType, resolverDictionary);
				}

				Resolver resolver = new Resolver
				{
					CreateInstanceFunc = () => Instantiate(toType),
					Singleton = singleton
				};

				resolverDictionary[key] = resolver;
				keyDictionary[key] = new WeakReference<Type>(fromType);
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : WeakReferencingContainer.cs
with MIT License
from CalciumFramework

public void Register<TInterface>(TInterface instance, string key = null)
		{
			key = GetKeyValueOrDefault(key);
			Type type = typeof(TInterface);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(type,
						out ResolverDictionary value))
				{
					value = new ResolverDictionary();
					typeDictionary.Add(type, value);
				}

				value[key] = new Resolver { CreateInstanceFunc = () => instance };
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : WeakReferencingContainer.cs
with MIT License
from CalciumFramework

public void Register<T>(
			Func<T> getInstanceFunc,
			bool singleton = false,
			string key = null)
		{
			replacedertArg.IsNotNull(getInstanceFunc, nameof(getInstanceFunc));

			key = GetKeyValueOrDefault(key);
			Type type = typeof(T);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(type,
					out ResolverDictionary resolverDictionary))
				{
					resolverDictionary = new ResolverDictionary();
				}

				Resolver resolver = new Resolver { Singleton = singleton };

				Func<object> getObjectFunc = () =>
				{
					if (cycleDictionary.TryGetValue(type, out List<string> keys))
					{
						if (keys.Contains(key))
						{
							/* TODO: Rather than throwing an exception, 
							 * we could Post the property set operation to the UI thread. */
							throw new ResolutionException(
								$"Cycle detected for {type} with key \"{key}\"");
						}

						keys.Add(key);
					}
					else
					{
						keys = new List<string> { key };
						cycleDictionary.Add(type, keys);
					}

					T result;
					try
					{
						result = getInstanceFunc();
					}
					finally
					{
						keys.Remove(key);
						if (!keys.Any())
						{
							cycleDictionary.Remove(type);
						}
					}

					if (resolver.Singleton)
					{
						resolver.CreateInstanceFunc = null;
						resolver.Instance = result;
					}

					return result;
				};

				resolver.CreateInstanceFunc = getObjectFunc;

				resolverDictionary[key] = resolver;
				keyDictionary[key] = new WeakReference<Type>(type);

				typeDictionary.SetValue(type, resolverDictionary);
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : WeakReferencingContainer.cs
with MIT License
from CalciumFramework

public void Register(
			Type type,
			Func<object> getInstanceFunc,
			bool singleton = false,
			string key = null)
		{
			replacedertArg.IsNotNull(type, nameof(type));
			replacedertArg.IsNotNull(getInstanceFunc, nameof(getInstanceFunc));

			key = GetKeyValueOrDefault(key);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(type,
						out ResolverDictionary resolverDictionary))
				{
					resolverDictionary = new ResolverDictionary();
				}

				Resolver resolver = new Resolver { Singleton = singleton };

				Func<object> getObjectFunc = () =>
				{
					var result = getInstanceFunc();

					if (resolver.Singleton)
					{
						resolver.CreateInstanceFunc = null;
						resolver.Instance = result;
					}

					return result;
				};

				resolver.CreateInstanceFunc = getObjectFunc;

				resolverDictionary[key] = resolver;
				keyDictionary[key] = new WeakReference<Type>(type);

				typeDictionary.SetValue(type, resolverDictionary);
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : WeakReferencingContainer.cs
with MIT License
from CalciumFramework

public void Register(Type type, object instance, string key = null)
		{
			replacedertArg.IsNotNull(type, nameof(type));

			key = GetKeyValueOrDefault(key);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(
						type, out ResolverDictionary value))
				{
					value = new ResolverDictionary();
				}

				Resolver info = new Resolver { CreateInstanceFunc = () => instance };

				value[key] = info;

				typeDictionary.SetValue(type, value);
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : WeakReferencingContainer.cs
with MIT License
from CalciumFramework

object Instantiate(Type type)
		{
			ConstructorInvokeInfo invokeInfo;

			bool useLock = ThreadSafe;
			if (useLock)
			{
				constructorDictionaryLockSlim.EnterReadLock();
			}

			try
			{
				if (constructorDictionary.TryGetValue(type, out invokeInfo))
				{
					return Instantiate(invokeInfo);
				}
			}
			finally
			{
				if (useLock)
				{
					constructorDictionaryLockSlim.ExitReadLock();
				}
			}

#if NETFX_CORE
			var constructors = type.GetTypeInfo().DeclaredConstructors.Where(x => !x.IsStatic && x.IsPublic).ToArray();
#else
			var constructors = type.GetTypeInfo().DeclaredConstructors;
#endif

			ConstructorInfo constructor = null;

			if (constructors.Any())
			{
				ConstructorInfo bestMatch = null;
				int biggestLength = -1;

				foreach (ConstructorInfo constructorInfo in constructors)
				{
					var dependencyAttributes = constructorInfo.GetCustomAttributes(typeof(InjectDependenciesAttribute), false).ToList();
					//#if NETSTANDARD || NETFX_CORE
					//					/* Unfortunately LINQ .Count() is much slower than .Length */
					//					var attributeCount = dependencyAttributes.Count();
					//#else
					//					var attributeCount = dependencyAttributes.Length;
					//#endif
					var attributeCount = dependencyAttributes.Count;
					bool hasAttribute = attributeCount > 0;

					if (hasAttribute)
					{
						constructor = constructorInfo;
						break;
					}

					var length = constructorInfo.GetParameters().Length;

					if (length > biggestLength)
					{
						biggestLength = length;
						bestMatch = constructorInfo;
					}
				}

				if (constructor == null)
				{
					constructor = bestMatch;
				}
			}
			else
			{
				ConstructorInfo bestMatch = null;
				int biggestLength = -1;

				constructors = type.GetTypeInfo().DeclaredConstructors.Where(x => !x.IsStatic && x.IsPrivate);

				foreach (ConstructorInfo constructorInfo in constructors)
				{
					var attributes = constructorInfo.GetCustomAttributes(typeof(InjectDependenciesAttribute), false);

					if (attributes.Any())
					{
						constructor = constructorInfo;
						break;
					}

					var length = constructorInfo.GetParameters().Length;

					if (length > biggestLength)
					{
						biggestLength = length;
						bestMatch = constructorInfo;
					}
				}

				if (constructor == null)
				{
					constructor = bestMatch;
				}
			}

			if (constructor == null)
			{
				throw new ResolutionException(
					"Could not locate a constructor for " + type.FullName);
			}

			invokeInfo = new ConstructorInvokeInfo(constructor);

			if (useLock)
			{
				constructorDictionaryLockSlim.EnterWriteLock();
			}

			try
			{
				constructorDictionary.SetValue(type, invokeInfo);
			}
			finally
			{
				if (useLock)
				{
					constructorDictionaryLockSlim.ExitWriteLock();
				}
			}

			return Instantiate(invokeInfo);
		}

19 Source : FrameworkContainer.cs
with MIT License
from CalciumFramework

public void Register(Type fromType, Type toType, 
			bool singleton = false, string key = null)
		{
			key = GetKeyValueOrDefault(key);

			bool useLock = ThreadSafe;
			if (useLock)
			{
				lockSlim.EnterWriteLock();
			}

			try
			{
				if (!typeDictionary.TryGetValue(fromType, 
						out ResolverDictionary resolverDictionary))
				{
					resolverDictionary = new ResolverDictionary();
					typeDictionary[fromType] = resolverDictionary;
				}

				Resolver resolver = new Resolver
				{
					CreateInstanceFunc = () => Instantiate(toType),
					Singleton = singleton
				};

				resolverDictionary[key] = resolver;
				keyDictionary[key] = fromType;
			}
			finally
			{
				if (useLock)
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : Messenger.cs
with MIT License
from CalciumFramework

public void Subscribe(object subscriber)
		{
			replacedertArg.IsNotNull(subscriber, nameof(subscriber));

			var weakReference = new WeakReference(subscriber);

			Type subscriberType = subscriber.GetType();

			List<Type> subscriptionInterfaces;
			if (!typeInterfaceCache.TryGetValue(subscriberType, out subscriptionInterfaces))
			{
				var implementedInterfaces = subscriberType.GetTypeInfo().ImplementedInterfaces;
				
				foreach (Type implementedInterface in implementedInterfaces)
				{
					if (implementedInterface.IsGenericType()
						&& implementedInterface.GetGenericTypeDefinition()
								== typeof(IMessageSubscriber<>))
					{
						if (subscriptionInterfaces == null)
						{
							subscriptionInterfaces = new List<Type>();
						}

						subscriptionInterfaces.Add(implementedInterface);
					}
				}

				typeInterfaceCache[subscriberType] = subscriptionInterfaces;
			}

			if (subscriptionInterfaces == null)
			{
				/* No IMessageSubscriber interfaces implemented by the subsciber type. */
				return;
			}

			lockSlim.EnterWriteLock();
			try
			{
				foreach (Type interfaceType in subscriptionInterfaces)
				{
					bool possibleDuplicate = false;
					List<Type> typesForThisMessage;
					if (registeredTypes.TryGetValue(interfaceType, out typesForThisMessage))
					{
						if (typesForThisMessage.Contains(subscriberType))
						{
							possibleDuplicate = true;
						}
					}
					else
					{
						typesForThisMessage = new List<Type>();
						registeredTypes[interfaceType] = typesForThisMessage;
					}

					typesForThisMessage.Add(subscriberType);

					List<WeakReference> subscribers = GetSubscribersNonLocking(interfaceType);

					if (possibleDuplicate)
					{
						/* We may want to improve search complexity here for large sets; 
						* perhaps using a ConditionalWeakTable. */
						foreach (WeakReference reference in subscribers)
						{
							if (reference.Target == subscriber)
							{
								return;
							}
						}
					}

					subscribers.Add(weakReference);
				}
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}
		}

19 Source : Messenger.cs
with MIT License
from CalciumFramework

public void Unsubscribe(object subscriber)
		{
			lockSlim.EnterWriteLock();
			try
			{
				foreach (KeyValuePair<Type, List<WeakReference>> pair in subscriberLists.ToList())
				{
					List<WeakReference> list = pair.Value;

					list?.RemoveAll(x => x.Target == subscriber);
				}
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}
		}

19 Source : Messenger.cs
with MIT License
from CalciumFramework

public async Task PublishAsync<TEvent>(TEvent eventToPublish,
			bool requireUIThread = false,
			Type recipientType = null,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			var subscriberType = typeof(IMessageSubscriber<>).MakeGenericType(typeof(TEvent));
			var subscribers = GetSubscribersLocking(subscriberType);
			List<WeakReference> subscribersToRemove = new List<WeakReference>();

			if (requireUIThread)
			{
				await UIContext.Instance.SendAsync(
					() => PublishCoreAsync(eventToPublish, subscribers, 
								subscribersToRemove, true, recipientType, 
								memberName, filePath, lineNumber));
			}
			else
			{
				await PublishCoreAsync(eventToPublish, subscribers, 
					subscribersToRemove, false, recipientType, 
					memberName, filePath, lineNumber).ConfigureAwait(false);
			}

			if (subscribersToRemove.Any())
			{
				lockSlim.EnterWriteLock();
				try
				{
					foreach (var remove in subscribersToRemove)
					{
						subscribers.Remove(remove);
					}
				}
				finally
				{
					lockSlim.ExitWriteLock();
				}
			}
		}

19 Source : StringParserService.cs
with MIT License
from CalciumFramework

void RegisterConverterCore(string tagName, IConverter converter)
		{
			try
			{
				convertersLock.EnterWriteLock();
				converters[tagName] = converter;
			}
			finally
			{
				convertersLock.ExitWriteLock();
			}
		}

19 Source : SettingsService.cs
with MIT License
from CalciumFramework

public void ClearCache()
		{
			lockSlim.EnterWriteLock();
			try
			{
				cache.Clear();
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}
		}

19 Source : SettingsService.cs
with MIT License
from CalciumFramework

public void RemoveCacheItem(string key)
		{
			string cacheKey = replacedertArg.IsNotNull(key, nameof(key));

			lockSlim.EnterWriteLock();
			try
			{
				cache.Remove(cacheKey);
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}
		}

19 Source : SettingsService.cs
with MIT License
from CalciumFramework

public bool RemoveSetting(string key)
		{
			replacedertArg.IsNotNull(key, nameof(key));

			bool result = false;

			lockSlim.EnterWriteLock();
			try
			{
				if (localStore.Status == SettingsStoreStatus.Ready)
				{
					result = localStore.Remove(key);
				}

				if (roamingStore != localStore && roamingStore != null && roamingStore.Status == SettingsStoreStatus.Ready)
				{
					result |= roamingStore.Remove(key);
				}

				if (transientStore != null && transientStore.Status == SettingsStoreStatus.Ready)
				{
					result |= transientStore.Remove(key);
				}

				cache.Remove(key);
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}

			if (result)
			{
				OnSettingRemoved(new SettingRemovedEventArgs(key));
			}

			return result;
		}

19 Source : SettingsService.cs
with MIT License
from CalciumFramework

public SetSettingResult SetSetting<T>(string key, T value, StorageLocation storageLocation = StorageLocation.Local)
		{
			Type settingType = typeof(T);
			var settingTypeInfo = settingType.GetTypeInfo();
			bool xmlConvertible = xmlConvertibleTypeInfo.IsreplacedignableFrom(settingTypeInfo);

			/* Check to see if the value is already set. 
			 * This avoids raising events unnecessarily. */
			bool alreadySet;

			lockSlim.EnterWriteLock();
			try
			{
				alreadySet = false;
				cache.Remove(key);

				if (localStore.Status == SettingsStoreStatus.Ready && localStore.TryGetValue(key, settingType, out object existingValue)
					|| (roamingStore != null && roamingStore.Status == SettingsStoreStatus.Ready && roamingStore.TryGetValue(key, settingType, out existingValue))
					|| (transientStore != null && transientStore.Status == SettingsStoreStatus.Ready && transientStore.TryGetValue(key, settingType, out existingValue)))
				{
					if (existingValue == null && value == null || existingValue != null && existingValue.Equals(value))
					{
						alreadySet = true;
					}
					else if (xmlConvertible)
					{
						if (existingValue != null)
						{
							Type concreteType = settingType.IsInterface() ? value?.GetType() : settingType;

							if (concreteType != null)
							{
								if (TryConvertFromXml(concreteType, existingValue, out object existingObject))
								{
									if (Equals(existingObject, value))
									{
										alreadySet = true;
									}
								}
							}
						}
					}
					else if (existingValue != null && settingType.IsEnum() && existingValue is int)
					{
						int intValue = (int)(object)value;//(int)Convert.ChangeType(value, typeof(int));
						if (AreEqual(intValue, existingValue))
						{
							alreadySet = true;
						}
					}
					else if (existingValue != null && existingValue is byte[] && settingType != typeof(byte[]))
					{
						var serializer = Dependency.Resolve<IBinarySerializer, BinarySerializer>();
						var existingObject = serializer.Deserialize<object>((byte[])existingValue);
						if (AreEqual(value, existingObject))
						{
							alreadySet = true;
						}
					}
				}
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}
			
			if (alreadySet)
			{
				return SetSettingResult.Successful;
			}

			/* Allows this action to be cancelled. */
			var args = new SettingChangingEventArgs(key, value);
			OnSettingChanging(args);

			if (args.Cancel)
			{
				Debug.WriteLine($"Setting change cancelled. Key: {key} New Value: {value}");
				return SetSettingResult.Cancelled;
			}

			lockSlim.EnterWriteLock();
			try
			{
				string cacheKey = key;
				cache[cacheKey] = value;

				if (storageLocation == StorageLocation.Transient)
				{
					if (transientStore.Status == SettingsStoreStatus.Ready)
					{
						SetTransientStateValue(transientStore, key, value);
					}
					else
					{
						/* SettingsService is being used before app is completely initialized. */
						UIContext.Instance.Post(delegate
						{
							if (transientStore.Status == SettingsStoreStatus.Ready)
							{
								SetTransientStateValue(transientStore, key, value);
							}
						});
					}
				}
				else
				{
					ISettingsStore store;
					if (storageLocation == StorageLocation.Roaming)
					{
						store = roamingStore ?? localStore;
					}
					else
					{
						store = localStore;
					}

					if (store.Status == SettingsStoreStatus.Ready)
					{
						SaveValueToStore(store, key, value, xmlConvertible, settingType);
					}
					else
					{
						/* We push the save value request onto the UI thread queue in case 
						 * some further initialization needs to occur. Otherwise it is up to 
						 * the ISettingsStore implementation to queue the update. */
						UIContext.Instance.Post(delegate
						{
							if (store.Status == SettingsStoreStatus.Ready)
							{
								SaveValueToStore(store, key, value, xmlConvertible, settingType);
							}
						});
					}
				}
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}

			OnSettingChanged(new SettingChangeEventArgs(key, value));

			return SetSettingResult.Successful;
		}

19 Source : SettingsService.cs
with MIT License
from CalciumFramework

public async Task ClearSettings()
		{
			lockSlim.EnterWriteLock();
			try
			{
				if (localStore.Status == SettingsStoreStatus.Ready)
				{
					await localStore.ClearAsync();
					await localStore.SaveAsync();
				}

				if (roamingStore != null && roamingStore != localStore
					&& roamingStore.Status == SettingsStoreStatus.Ready)
				{
					await roamingStore.ClearAsync();
					await roamingStore.SaveAsync();
				}

				if (transientStore.Status == SettingsStoreStatus.Ready)
				{
					await transientStore.ClearAsync();
					await transientStore.SaveAsync();
				}
			}
			finally
			{
				lockSlim.ExitWriteLock();
			}

			ClearCache();
		}

19 Source : ReaderWriterLockSlimExtensions.cs
with MIT License
from CalciumFramework

public static void WriteLock(
			this ReaderWriterLockSlim readerWriterLockSlim, 
			Action action)
		{
			readerWriterLockSlim.EnterWriteLock();
			try
			{
				action();
			}
			finally
			{
				readerWriterLockSlim.ExitWriteLock();
			}
		}

19 Source : ReaderWriterLockSlimExtensions.cs
with MIT License
from CalciumFramework

public static async Task WriteLockAsync(
			this ReaderWriterLockSlim readerWriterLockSlim, 
			Func<Task> func)
		{
			readerWriterLockSlim.EnterWriteLock();
			try
			{
				await func();
			}
			finally
			{
				readerWriterLockSlim.ExitWriteLock();
			}
		}

19 Source : ReaderWriterLockSlimExtensions.cs
with MIT License
from CalciumFramework

public static T WriteLock<T>(
			this ReaderWriterLockSlim readerWriterLockSlim, 
			Func<T> func)
		{
			readerWriterLockSlim.EnterWriteLock();
			try
			{
				return func();
			}
			finally
			{
				readerWriterLockSlim.ExitWriteLock();
			}
		}

19 Source : ReaderWriterLockSlimExtensions.cs
with MIT License
from CalciumFramework

public static async Task<T> WriteLockAsync<T>(
			this ReaderWriterLockSlim readerWriterLockSlim, 
			Func<Task<T>> func)
		{
			readerWriterLockSlim.EnterWriteLock();
			try
			{
				return await func();
			}
			finally
			{
				readerWriterLockSlim.ExitWriteLock();
			}
		}

19 Source : ViewBinderRegistry.cs
with MIT License
from CalciumFramework

public bool RemoveViewBinder(Type viewType, string propertyName)
		{
			string key = MakeDictionaryKey(viewType, propertyName);

			dictionaryLock.EnterWriteLock();
			try
			{
				return binderDictionary.Remove(key);
			}
			finally
			{
				dictionaryLock.ExitWriteLock();
			}
		}

19 Source : RoutingService.cs
with MIT License
from CalciumFramework

public void RegisterPath(string url, Action<object> navigationAction)
		{
			replacedertArg.IsNotNullOrWhiteSpace(url, nameof(url));
			replacedertArg.IsNotNull(navigationAction, nameof(navigationAction));

			dictionaryLock.EnterWriteLock();
			try
			{
				pathDictionary[url] = navigationAction;
			}
			finally
			{
				dictionaryLock.ExitWriteLock();
			}
		}

19 Source : ViewBinderRegistry.cs
with MIT License
from CalciumFramework

public bool TryGetViewBinder(Type viewType, string propertyName, out IViewBinder viewBinder)
		{
			string key = MakeDictionaryKey(viewType, propertyName);

			try
			{
				dictionaryLock.EnterUpgradeableReadLock();

				if (binderDictionary.TryGetValue(key, out viewBinder))
				{
					return true;
				}

				if (implicityBinderDictionary.TryGetValue(key, out viewBinder))
				{
					return true;
				}

				foreach (var pair in binderDictionary)
				{
					string name = pair.Key;
					if (!name.EndsWith(propertyName))
					{
						continue;
					}

					var binder = pair.Value;
					var type = binder.ViewType;
					if (type != null && type.IsreplacedignableFromEx(viewType))
					{
						string newItemKey = MakeDictionaryKey(viewType, propertyName);
						
						try
						{
							dictionaryLock.EnterWriteLock();

							implicityBinderDictionary[newItemKey] = binder;
						}
						finally
						{
							dictionaryLock.ExitWriteLock();
						}
						
						viewBinder = binder;

						return true;
					}
				}
			}
			finally
			{
				dictionaryLock.ExitUpgradeableReadLock();
			}

			return false;
		}

19 Source : ViewBinderRegistry.cs
with MIT License
from CalciumFramework

public void SetViewBinder<TView>(string propertyName, IViewBinder viewBinder)
		{
			string key = typeof(TView).replacedemblyQualifiedName + "." + propertyName;

			dictionaryLock.EnterWriteLock();
			try
			{
				binderDictionary[key] = viewBinder;
			}
			finally
			{
				dictionaryLock.ExitWriteLock();
			}
		}

19 Source : ViewBinderRegistry.cs
with MIT License
from CalciumFramework

public void SetViewBinder(Type viewType, string propertyName, IViewBinder viewBinder)
		{
			string key = MakeDictionaryKey(viewType, propertyName);

			dictionaryLock.EnterWriteLock();
			try
			{
				binderDictionary[key] = viewBinder;
			}
			finally
			{
				dictionaryLock.ExitWriteLock();
			}
		}

19 Source : ViewBinderRegistry.cs
with MIT License
from CalciumFramework

public void SetViewBinders(IDictionary<PropertyDescriptor, IViewBinder> binders)
		{
			dictionaryLock.EnterWriteLock();
			try
			{
				foreach (KeyValuePair<PropertyDescriptor, IViewBinder> pair in binders)
				{
					var path = pair.Key;
					string key = MakeDictionaryKey(path.ViewType, path.PropertyName);
					binderDictionary[key] = pair.Value;
				}
			}
			finally
			{
				dictionaryLock.ExitWriteLock();
			}
		}

19 Source : RollingWindow.cs
with Apache License 2.0
from Capnode

public void Reset()
        {
            try
            {
                _listLock.EnterWriteLock();

                _samples = 0;
                _list.Clear();
                _tail = 0;
            }
            finally
            {
                _listLock.ExitWriteLock();
            }
        }

19 Source : RollingWindow.cs
with Apache License 2.0
from Capnode

public void Add(T item)
        {
            try
            {
                _listLock.EnterWriteLock();

                _samples++;
                if (Size == Count)
                {
                    // keep track of what's the last element
                    // so we can reindex on this[ int ]
                    _mostRecentlyRemoved = _list[_tail];
                    _list[_tail] = item;
                    _tail = (_tail + 1) % Size;
                }
                else
                {
                    _list.Add(item);
                }
            }
            finally
            {
                _listLock.ExitWriteLock();
            }
        }

19 Source : ReaderWriterLockSlimExtensions.cs
with Apache License 2.0
from Capnode

protected override void EnterLock(ReaderWriterLockSlim readerWriterLockSlim)
            {
                readerWriterLockSlim.EnterWriteLock();
            }

19 Source : CefBaseRefCounted.cs
with MIT License
from CefNet

public unsafe static TClreplaced Wrap<TClreplaced>(Func<IntPtr, TClreplaced> create, T* instance)
			where TClreplaced : CefBaseRefCounted<T>
		{
			if (instance == null)
				return null;

			RefCountedWrapperStruct* ws = null;
			CefBaseRefCounted wrapper;
			IntPtr key = new IntPtr(instance);
			Internal.CefBaseRefCountedImpl.GlobalSyncRoot.EnterUpgradeableReadLock();
			try
			{
				if (CefApi.UseUnsafeImplementation)
				{
					ws = GetWrapperStructPtr(instance);
					if (ws != null && UnsafeRefCounted.TryGetValue(ws->cppObject, out WeakReference<CefBaseRefCounted> weakRef)
						&& weakRef.TryGetTarget(out wrapper))
					{
						((cef_base_ref_counted_t*)instance)->Release();
						return (TClreplaced)wrapper;
					}
				}

				if (RefCounted.TryGetValue(key, out RefCountedReference reference)
					&& reference.Instance.TryGetTarget(out wrapper))
				{
					((cef_base_ref_counted_t*)instance)->Release();
					return (TClreplaced)wrapper;
				}
#if DEBUG
				else if (CefStructure.IsAllocated(key))
				{
					throw new InvalidCefObjectException(string.Format("Unexpected access to {0}.", typeof(TClreplaced).Name));
				}
#endif
				else
				{
					Internal.CefBaseRefCountedImpl.GlobalSyncRoot.EnterWriteLock();
					try
					{
						TClreplaced typedWrapper = create(key);
						var weakRef = new WeakReference<CefBaseRefCounted>(typedWrapper);
						RefCounted[key] = new RefCountedReference(weakRef);
						if (ws != null)
						{
							UnsafeRefCounted[ws->cppObject] = weakRef;
						}
						return typedWrapper;
					}
					finally
					{
						Internal.CefBaseRefCountedImpl.GlobalSyncRoot.ExitWriteLock();
					}
				}
			}
			finally
			{
				Internal.CefBaseRefCountedImpl.GlobalSyncRoot.ExitUpgradeableReadLock();
			}
		}

19 Source : CefBaseRefCounted.cs
with MIT License
from CefNet

protected unsafe override void Dispose(bool disposing)
		{
			IntPtr key = Volatile.Read(ref _instance);
			if (key != IntPtr.Zero)
			{
				GlobalSyncRoot.EnterWriteLock();
				try
				{
					if (CefApi.UseUnsafeImplementation)
					{
						RefCountedWrapperStruct* ws = GetWrapperStructPtr((void*)key);
						if (ws != null) UnsafeRefCounted.Remove(ws->cppObject);
					}
					RefCounted.Remove(key);
				}
				finally
				{
					GlobalSyncRoot.ExitWriteLock();
				}
#if NETFRAMEWORK
				if (Environment.HreplacedhutdownStarted)
				{
					if (CefStructure.IsAllocated(key)) // allow leaks to fix potential UAF
						return;
				}
				else
#endif
				if (CefStructure.Free(key))
					return;

				base.Dispose(disposing);
			}
		}

See More Examples