public INode Lookup(object obj) { List <INode> value; if (_lookupCache.TryGetValue(obj, out @value)) { return(@value.FirstOrDefault()); } return(null); }
/// <summary> /// Creates an instance of the type with the specified constructor arguments. /// </summary> /// <param name = "type">The type.</param> /// <param name = "args">The constructor args.</param> /// <returns>The created instance.</returns> protected override object ActivateInstance(Type type, object[] args) { object result; if (_singletones.TryGetValue(type, out result)) { return(result); } RegisterAsKind kind; lock (_syncObject) { if (!_types.TryGetValue(type, out kind)) { kind = GetKind(type); _types.Add(type, kind); } } result = base.ActivateInstance(type, args); if (kind == RegisterAsKind.Singleton) { _singletones.Add(type, result); } return(result); }
public object GetValue() { if (Data == null) { return(null); } if (SerializedObjects.TryGetValue(Data, out var value)) { return(value); } var type = string.IsNullOrWhiteSpace(DataType) ? typeof(object) : Core.GetType(DataType, true); if (string.IsNullOrWhiteSpace(SerializerMimeType)) { return(type == typeof(byte[]) ? Data : null); } var idx = SerializerMimeType.IndexOf(':'); var serMime = idx < 0 ? SerializerMimeType : SerializerMimeType.Substring(0, idx); var serComp = idx < 0 ? null : SerializerMimeType.Substring(idx + 1); var serializer = SerializerManager.GetByMimeType(serMime); if (serializer == null) { throw new FormatException($"The serializer with MimeType = {serMime} wasn't found."); } if (!string.IsNullOrWhiteSpace(serComp)) { serializer.Compressor = CompressorManager.GetByEncodingType(serComp); } value = serializer.Deserialize(Data, type); SerializedObjects.TryAdd(Data, value); return(value); }
internal static LinkedList <WeakReference> GetAttributeInterfaces(Type clazz) { LinkedList <WeakReference> foundInterfaces; lock (KnownImplClasses) { KnownImplClasses.TryGetValue(clazz, out foundInterfaces); if (foundInterfaces == null) { // we have the slight chance that another thread may do the same, but who cares? foundInterfaces = new LinkedList <WeakReference>(); // find all interfaces that this attribute instance implements // and that extend the Attribute interface Type actClazz = clazz; do { foreach (Type curInterface in actClazz.GetInterfaces()) { if (curInterface != typeof(IAttribute) && (typeof(IAttribute)).IsAssignableFrom(curInterface)) { foundInterfaces.AddLast(new WeakReference(curInterface)); } } actClazz = actClazz.BaseType; } while (actClazz != null); KnownImplClasses[clazz] = foundInterfaces; } } return(foundInterfaces); }
public Delegate CreateDelegate(Type delegateType, object dynamicObject) { Assert.NotNull(delegateType, dynamicObject); object[] closure; lock (_closureMap) { if (!_closureMap.TryGetValue(dynamicObject, out WeakReference weakClosure) || (closure = (object[])weakClosure.Target) == null) { closure = new[] { TargetPlaceHolder, CallSitePlaceHolder, ConvertSitePlaceHolder }; _closureMap[dynamicObject] = new WeakReference(closure); Type[] siteTypes = MakeSiteSignature(_parameterTypes); CallSite callSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(siteTypes), _invokeBinder); CallSite convertSite = null; if (_returnType != typeof(void)) { convertSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(typeof(object), _returnType), _convertBinder); } closure[TargetIndex] = dynamicObject; closure[CallSiteIndex] = callSite; closure[ConvertSiteIndex] = convertSite; } } return(_method.CreateDelegate(delegateType, closure)); }
/// <seealso cref="NotifyPropertyChangeFactory.GetProxy{T}(T)"/> internal static T GetProxy(T target) { if (target == null) { return(null); } if (_proxyType == null) { Init(); } if (target.GetType() == _proxyType) { return(target); } lock (_cache) { T proxy; if (!_cache.TryGetValue(target, out proxy)) { proxy = _newProxy(target); _cache[target] = proxy; } return(proxy); } }
internal Delegate CreateDelegate(Type delegateType, object target) { Assert.NotNull(delegateType, target); // to enable: // function x() { } // someClass.someEvent += delegateType(x) // someClass.someEvent -= delegateType(x) // // we need to avoid re-creating the object array because they won't // be compare equal when removing the delegate if they're difference // instances. Therefore we use a weak hashtable to get back the // original object array. The values also need to be weak to avoid // creating a circular reference from the constants target back to the // target. This is fine because as long as the delegate is referenced // the object array will stay alive. Once the delegate is gone it's not // wired up anywhere and -= will never be used again. object[] clone; lock (_constantMap) { WeakReference cloneRef; if (!_constantMap.TryGetValue(target, out cloneRef) || (clone = (object[])cloneRef.Target) == null) { _constantMap[target] = new WeakReference(clone = (object[])_constants.Clone()); Debug.Assert(clone[0] == DelegateSignatureInfo.TargetPlaceHolder); clone[0] = target; } } return(ReflectionUtils.CreateDelegate(_method, delegateType, clone)); }
private static ArrayType /*!*/ MakeArrayType(PythonType type, int count) { if (count < 0) { throw PythonOps.ValueError("cannot multiply ctype by negative number"); } lock (_arrayTypes) { if (!_arrayTypes.TryGetValue(type, out Dictionary <int, ArrayType> countDict)) { _arrayTypes[type] = countDict = new Dictionary <int, ArrayType>(); } if (!countDict.TryGetValue(count, out ArrayType res)) { res = countDict[count] = new ArrayType(type.Context.SharedContext, type.Name + "_Array_" + count, PythonTuple.MakeTuple(Array), PythonOps.MakeDictFromItems(new object[] { type, "_type_", count, "_length_" }) ); } return(res); } }
public void HitBy(Player player, RealmTime time, Projectile projectile, int dmg) { int totalDmg; if (!hitters.TryGetValue(player, out totalDmg)) { totalDmg = 0; } totalDmg += dmg; hitters[player] = totalDmg; LastProjectile = projectile; LastHitter = player; player.FameCounter.Hit(projectile, enemy); }
private static Delegate GenerateDelegateForInterpreter(InterpreterState state, LambdaExpression lambda) { if (_Delegates == null) { Interlocked.CompareExchange <WeakDictionary <LambdaExpression, MethodInfo> >( ref _Delegates, new WeakDictionary <LambdaExpression, MethodInfo>(), null ); } bool found; MethodInfo method; // // LOCK to find the MethodInfo // lock (_Delegates) { found = _Delegates.TryGetValue(lambda, out method); } if (!found) { method = CreateDelegateForInterpreter(lambda.Type); // // LOCK to store the MethodInfo // (and maybe find one added while we were creating new delegate, in which case // throw away the new one and use the one from the cache. // lock (_Delegates) { MethodInfo conflict; if (!_Delegates.TryGetValue(lambda, out conflict)) { _Delegates.Add(lambda, method); } else { method = conflict; } } } return(ReflectionUtils.CreateDelegate(method, lambda.Type, new LambdaInvoker(lambda, state))); }
/// <summary> /// Gets the value of the specified key. /// </summary> /// <param name="key">The key that represents an object with an attached property.</param> /// <param name="value">When this method returns, contains the attached property value. If key is not found, value contains the default value.</param> /// <returns> /// <c>true</c> if the key is found; otherwise, <c>false</c>. /// </returns> public bool TryGetValue(TKey key, out TValue value) { if (key == null) { throw new ArgumentNullException("key"); } return(_wrapped.TryGetValue(key, out value)); }
// ReSharper disable UnusedMember.Local private bool IsInfoCardOpen(DependencyObject obj) { if (obj == null) { return(false); } var infoCardSubject = GetInfoCardSubject(obj); if (infoCardSubject == null) { return(false); } InfoCard infoCard; return(_infoCardCache.TryGetValue(infoCardSubject, out infoCard) && infoCard.IsOpen); }
public void TryGetValue_ReferenceNotFound() { var dictionary = new WeakDictionary<object, object>(); object v; bool result = dictionary.TryGetValue(new Object(), out v); Assert.AreEqual(false, result); Assert.AreEqual(null, v); Assert.AreEqual(false, dictionary.Contains(new Object())); }
/// <summary> /// Creates a "transparent" proxy of the specified type, returning it as a ProxyObject /// </summary> /// <param name="t">The type to make a transparent proxy of</param> /// <param name="id">The id to pass the proxy</param> /// <param name="handler">The handler that will manage the proxy</param> /// <returns>A proxy object implementing the specified interface</returns> public static ProxyObject CreateProxy(Type t, long id, IProxyHandler handler) { if (!_builders.TryGetValue(t, out var builder)) { _builders[t] = builder = (Func <long, IProxyHandler, ProxyObject>) _create_object.MakeGenericMethod(t) .CreateDelegate(typeof(Func <long, IProxyHandler, ProxyObject>)); } return(builder.Invoke(id, handler)); }
public void TryGetValue_ReferenceNotFound() { var dictionary = new WeakDictionary <object, object>(); object v; bool result = dictionary.TryGetValue(new Object(), out v); Assert.Equal(false, result); Assert.Equal(null, v); Assert.Equal(false, dictionary.Contains(new Object())); }
private static ClassAnnotation GetOrCreateAnnotation(object key) { _annotations.RemoveCollectedEntries(); ClassAnnotation annotation; if (!_annotations.TryGetValue(key, out annotation)) { lock (_annotations) { if (!_annotations.TryGetValue(key, out annotation)) { annotation = new ClassAnnotation(key); _annotations.Add(key, annotation); } } } return(annotation); }
internal Delegate CreateDelegate(Type delegateType, object target) { Assert.NotNull(delegateType, target); // to enable: // function x() { } // someClass.someEvent += delegateType(x) // someClass.someEvent -= delegateType(x) // // we need to avoid re-creating the object array because they won't // be compare equal when removing the delegate if they're difference // instances. Therefore we use a weak hashtable to get back the // original object array. The values also need to be weak to avoid // creating a circular reference from the constants target back to the // target. This is fine because as long as the delegate is referenced // the object array will stay alive. Once the delegate is gone it's not // wired up anywhere and -= will never be used again. object[] clone; lock (_constantMap) { WeakReference cloneRef; if (!_constantMap.TryGetValue(target, out cloneRef) || (clone = (object[])cloneRef.Target) == null) { _constantMap[target] = new WeakReference(clone = (object[])_constants.Clone()); Type[] siteTypes = MakeSiteSignature(); CallSite callSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(siteTypes), _invokeBinder); Type siteType = callSite.GetType(); Type convertSiteType = null; CallSite convertSite = null; if (_returnType != typeof(void)) { convertSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(typeof(object), _returnType), _convertBinder); convertSiteType = convertSite.GetType(); } Debug.Assert(clone[0] == TargetPlaceHolder); Debug.Assert(clone[1] == CallSitePlaceHolder); Debug.Assert(clone[2] == ConvertSitePlaceHolder); clone[0] = target; clone[1] = callSite; clone[2] = convertSite; } } return(ReflectionUtils.CreateDelegate(_method, delegateType, clone)); }
public ResponseMessage GetCompleteMessage(object messageBody) { if (messageBody == null) { return(null); } if (_receivedMessagesCache.TryGetValue(messageBody, out var _out)) { return((ResponseMessage)_out); } return(null); }
public void TryGetValue_ReferenceFound() { object k1 = new Object(); object v1 = new Object(); var dictionary = new WeakDictionary<object, object>(); dictionary[k1] = v1; // Now look for the same key we inserted object v2; bool result = dictionary.TryGetValue(k1, out v2); Assert.Equal(true, result); Assert.Equal(true, Object.ReferenceEquals(v1, v2)); }
public void TryGetValue_ReferenceFound() { object k1 = new Object(); object v1 = new Object(); var dictionary = new WeakDictionary <object, object>(); dictionary[k1] = v1; // Now look for the same key we inserted object v2; bool result = dictionary.TryGetValue(k1, out v2); Assert.Equal(true, result); Assert.Equal(true, Object.ReferenceEquals(v1, v2)); }
public static bool TryGetLuaString(IntPtr p, out string result) { LuaString ls; bool ret = weakDictionary.TryGetValue((long)p, out ls); if (ret) { result = ls.value; } else { result = string.Empty; } return(ret); }
public static T Get <T>(this object obj) where T : new() { if (obj == null) { return(default(T)); } lock ( Sync ) { if (DynamicFields.TryGetValue(obj, out object value)) { if (value is Dictionary <Type, object> existingDictionary) { if (existingDictionary.TryGetValue(typeof(T), out value)) { return((T)value); } else { var t = new T(); existingDictionary[typeof(T)] = t; return(t); } } if (!(value is T)) { var newDictionary = new Dictionary <Type, object>(); newDictionary.Add(value.GetType(), value); var t = new T(); newDictionary[typeof(T)] = t; DynamicFields[obj] = newDictionary; return(t); } else { return((T)value); } } else { var t = new T(); DynamicFields[obj] = t; return(t); } } }
public static T Get <T>(this object obj) where T : new() { lock ( Sync ) { if (DynamicFields.TryGetValue(obj, out object value)) { return((T)value); } else { var t = new T(); DynamicFields[obj] = t; return(t); } } }
public virtual ShapeFieldCache <T> GetCache(AtomicReader reader) { lock (locker) { ShapeFieldCache <T> idx; if (sidx.TryGetValue(reader, out idx) && idx != null) { return(idx); } /*long startTime = Runtime.CurrentTimeMillis(); * log.Fine("Building Cache [" + reader.MaxDoc() + "]");*/ idx = new ShapeFieldCache <T>(reader.MaxDoc, m_defaultSize); int count = 0; DocsEnum docs = null; Terms terms = reader.GetTerms(m_shapeField); TermsEnum te = null; if (terms != null) { te = terms.GetIterator(te); BytesRef term = te.Next(); while (term != null) { T shape = ReadShape(term); if (shape != null) { docs = te.Docs(null, docs, DocsFlags.NONE); int docid = docs.NextDoc(); while (docid != DocIdSetIterator.NO_MORE_DOCS) { idx.Add(docid, shape); docid = docs.NextDoc(); count++; } } term = te.Next(); } } sidx[reader] = idx; /*long elapsed = Runtime.CurrentTimeMillis() - startTime; * log.Fine("Cached: [" + count + " in " + elapsed + "ms] " + idx);*/ return(idx); } }
public void TryGetRemovesDeadValue() { object k = new Object(); object v = new Object(); var dictionary = new WeakDictionary <object, object>(); dictionary[k] = v; // Do not put an assert here! It will cause the test to mysteriously fail // as somehow an NUnit Assert can hold onto the value! v = null; GC.Collect(); object value; Assert.Equal(false, dictionary.TryGetValue(k, out value)); Assert.Equal(0, dictionary.Count); }
/// <summary> /// Returns a Func<T,R> that wraps func. Each time the resulting /// Func<T,R> is called with a new value, its result is memoized (cached). /// Subsequent calls use the memoized value. /// /// Remarks: /// Thread-safe and memory-leak safe. /// R is limited to reference types. /// </summary> public static Func <T, R> memo <T, R>(this Func <T, R> func) where R : class { var cache = new WeakDictionary <T, R>(); var syncMap = new ConcurrentDictionary <T, object>(); return(inp => { R res; if (!cache.TryGetValue(inp, out res)) { var sync = syncMap.GetOrAdd(inp, new object()); lock (sync) { res = cache.GetOrAdd(inp, func); } syncMap.TryRemove(inp, out sync); } return res; }); }
public static Func <T, R> memo <T, R>(Func <T, R> func) { var cache = new WeakDictionary <T, R>(); var syncMap = new ConcurrentDictionary <T, object>(); return(inp => cache.TryGetValue(inp).Match( some: x => x, none: () => { R res; var sync = syncMap.GetOrAdd(inp, new object()); lock (sync) { res = cache.GetOrAdd(inp, func); } syncMap.TryRemove(inp, out sync); return res; })); }
internal static Type GetClassForInterface <T>() where T : IAttribute { var attClass = typeof(T); WeakReference @ref; AttClassImplMap.TryGetValue(attClass, out @ref); Type clazz = (@ref == null) ? null : (Type)@ref.Target; if (clazz == null) { // we have the slight chance that another thread may do the same, but who cares? try { string name = attClass.FullName.Replace(attClass.Name, attClass.Name.Substring(1)) + ", " + attClass.Assembly.FullName; AttClassImplMap.Add(attClass, new WeakReference(clazz = Type.GetType(name, true))); } catch (Exception) { throw new System.ArgumentException("Could not find implementing class for " + attClass.Name); } } return(clazz); }
protected override object InternalGetValue(object instance) { if (instance == null) { throw new ArgumentNullException("instance", "instance is null."); } object value; if (!data.TryGetValue(instance, out value)) { if (propertyType.IsValueType) { return(Activator.CreateInstance(propertyType)); } else { return(null); } } return(value); }
public void Update() { if (networkView.isMine) { WeaponIndicatorScript.Instance.ShouldRender = Possession != null; UpdateShouldCameraSpin(); Relay.Instance.OptionsMenu.ShouldDisplaySpectateButton = !IsSpectating; if (Possession == null) { if (Input.GetButtonDown("Fire") && !IsSpectating) { IndicateRespawn(); } } // Update player labels if (Camera.current != null) { foreach (var playerScript in PlayerScript.UnsafeAllEnabledPlayerScripts) { if (playerScript == null) { continue; } Vector3 position = Camera.current.WorldToScreenPoint(InfoPointForPlayerScript(playerScript)); Vector2 prevScreenPosition; if (!LastGUIDebugPositions.TryGetValue(playerScript, out prevScreenPosition)) { prevScreenPosition = (Vector2)position; } Vector2 newScreenPosition = Vector2.Lerp(prevScreenPosition, (Vector2)position, 1f - Mathf.Pow(0.0000000001f, Time.deltaTime)); LastGUIDebugPositions[playerScript] = newScreenPosition; } } IsDoingMenuStuff = Relay.Instance.MessageLog.HasInputOpen; // Debug visibility info for other playerscripts if (Possession != null) { foreach (var character in PlayerScript.UnsafeAllEnabledPlayerScripts) { if (character != Possession) { bool canSee = Possession.CanSeeOtherPlayer(character); if (canSee) { ScreenSpaceDebug.AddMessageOnce("VISIBLE", character.transform.position); } } } } // Leaderboard show/hide // Always show when not possessing anything // Never show when already showing options screen if (Possession == null || TimeToHoldLeaderboardFor >= 0f) { Server.Leaderboard.Show = true; } // Otherwise, show when holding tab else { Server.Leaderboard.Show = Input.GetKey("tab") && !Relay.Instance.ShowOptions; } TimeToHoldLeaderboardFor -= Time.deltaTime; // TODO test this in a multiplayer environment // if game is no longer active, i.e., round end or host forced end, then if (!this.Server.IsGameActive) { // force mouse state to be unlocked //playerScript.lockMouse = false; Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } //if (!Relay.Instance.ShowOptions && Possession != null && !ShouldDisplayJoinPanel) // playerScript.lockMouse = true; // if (ShouldDisplayJoinPanel || Relay.Instance.ShowOptions || !Server.IsGameActive) // playerScript.lockMouse = false; // Update ping Ping = uLink.Network.GetAveragePing(Server.networkView.owner); } if (Possession != null) { // toggle bubble Possession.TextBubbleVisible = IsDoingMenuStuff; } if (Input.GetKeyDown("f11")) { ScreenSpaceDebug.LogMessageSizes(); } TimeSinceLastRespawnRequest += Time.deltaTime; }
private void RaiseInfoCardOpeningEvent() { ResetInfoCardTimer(); var lastMouseOver = LastMouseOverWithInfoCard; if (lastMouseOver != null) { var showInfoCard = true; var inputElement = lastMouseOver as IInputElement; if (inputElement != null) { // Raise the screen tip opening event var e = new RoutedEventArgs(InfoCardOpeningEvent, this); inputElement.RaiseEvent(e); showInfoCard = !e.Handled; } if (showInfoCard) { if ((_currentInfoCard != null) && !_currentInfoCard.IsOpen) { RetireInfoCard(_currentInfoCard); } _currentInfoCard = CreateInfoCard(lastMouseOver); if (_currentInfoCard != null) { var targetElement = lastMouseOver as UIElement; _currentInfoCard.TargetElement = targetElement; var infoCardPosition = Mouse.GetPosition(inputElement); var infoCardSite = _currentInfoCard.RegisteredInfoCardSite ?? lastMouseOver.FindVisualAncestorByType <InfoCardSite>(); if (infoCardSite == null) { var window = Window.GetWindow(lastMouseOver); if (window != null) { if (!_generatedSites.TryGetValue(window, out infoCardSite)) { infoCardSite = new InfoCardSite(); _generatedSites[window] = infoCardSite; } } else { RetireInfoCard(_currentInfoCard); _currentInfoCard = null; return; } } if (!_currentInfoCard.IsOpen) { if (!infoCardSite.InfoCards.Contains(_currentInfoCard)) { SetUnregisterInfoCardOnClose(_currentInfoCard, true); infoCardSite.InfoCards.Add(_currentInfoCard); } } if (infoCardSite.IsLoaded) { var targetVisual = targetElement; if (targetVisual != null) { var transformToVisual = targetVisual.TransformToVisual(infoCardSite); if (transformToVisual != null) { infoCardPosition = transformToVisual.Transform(infoCardPosition); } } } if (targetElement != null) { var customPlacementCallback = _currentInfoCard.CustomPlacementCallback ?? GetCustomInfoCardPlacementCallback(targetElement); if (customPlacementCallback != null) { _currentInfoCard.UpdateLayout(); infoCardPosition = customPlacementCallback( _currentInfoCard.RenderSize, targetElement, infoCardPosition); } } _currentInfoCard.Location = new Point( DoubleUtil.DoubleToInt(infoCardPosition.X), DoubleUtil.DoubleToInt(infoCardPosition.Y)); if (_currentInfoCard.IsOpen) { var infoCardWindow = InfoCardHost.GetInfoCardWindow(_currentInfoCard); if (infoCardWindow != null) { infoCardWindow.Setup(_currentInfoCard.Location); infoCardWindow.Activate(); } return; } _currentInfoCard.Open(); } } } }
public void TryGetRemovesDeadValue() { object k = new Object(); object v = new Object(); var dictionary = new WeakDictionary<object, object>(); dictionary[k] = v; // Do not put an assert here! It will cause the test to mysteriously fail // as somehow an NUnit Assert can hold onto the value! v = null; GC.Collect(); object value; Assert.Equal(false, dictionary.TryGetValue(k, out value)); Assert.Equal(0, dictionary.Count); }
public bool TryGetValue(WeakDictionary <object, int, object> d, Tuple <object, int> k, out object v) { return(d.TryGetValue(k.Item1, k.Item2, out v)); }