static void Init() { if (slots == null) { slots = new WeakDictionary <ThreadLocal <T>, T>(); } }
private static void Init() { lock (_initLock) _isInitialized = true; _cache = new WeakDictionary <T, T>(new ReferenceEqualityComparer <T>()); RegisterCache(_cache); var @interface = typeof(T); if ([email protected]) { throw new InvalidOperationException(@interface + " is not an interface type."); } Emitter e = new Emitter(_moduleBuilder); _proxyType = e.Generate(new Generator <T> { g = e }.DefineProxy()); var constructor = _proxyType.GetConstructor(new[] { @interface }); var dynamicConstructor = new DynamicMethod( "NewProxyDynamic", @interface, new[] { @interface }, _proxyType); var il = dynamicConstructor.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Newobj, constructor); il.Emit(OpCodes.Ret); _newProxy = (Converter <T, T>)dynamicConstructor.CreateDelegate(typeof(Converter <T, T>)); _getTarget = (Converter <T, T>)Delegate.CreateDelegate( typeof(Converter <T, T>), _proxyType.GetMethod("GetTarget")); }
public void TestAddANullKeyThrowsException() { WeakDictionary <KeyObject, int> weakDict = new WeakDictionary <KeyObject, int>(this.comparer, 5); Action testAction = () => { weakDict.Add(null, 10); }; testAction.ShouldThrow <ArgumentNullException>(); }
private void AddTupleObject(WeakDictionary <object, int> dict, int id) { KeyObject key = new KeyObject(id); var tuple = new Tuple <object, MemberInfo>(key, this.memberInfo); dict.Add(tuple, rand.Next()); }
public void TestRemoveDeadItemWhenAddMoreThanRefreshIntervalItems() { WeakDictionary <object, int> weakDict = new WeakDictionary <object, int>(this.comparer, 5); for (int i = 0; i < 2; i++) { AddKeyObject(weakDict, i); } for (int i = 0; i < 3; i++) { AddTupleObject(weakDict, i); } // Force gc to collect dead items GC.Collect(); if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded) { var key = new KeyObject(6); weakDict.Add(key, 6); // The countLimit after the first clean is 6 now. Assert.AreEqual(1, weakDict.Count); } }
public override void Given() { dictionary = new WeakDictionary<object, object> { {key1, value1}, {key2, value2} }; }
public void RegistrationDoesNotPreventGarbageCollection() { WeakDictionary <object, object> dict = new WeakDictionary <object, object>(); dict.Add("foo", new object()); GC.Collect(); object unused = dict["foo"]; }
public override void Given() { dictionary = new WeakDictionary <object, object> { { key1, value1 }, { key2, value2 } }; }
private InfoCardService() { _generatedSites = new WeakDictionary <Window, InfoCardSite>(); _infoCardCache = new WeakDictionary <IInfoCardSubject, InfoCard>( new DelegatingEqualityComparer <IInfoCardSubject>( (x, y) => (x == null) ? (y == null) : Equals(x.Data, y.Data), s => (s.Data != null) ? s.Data.GetHashCode() : 0)); }
public void AddingToSameKeyTwiceAlwaysThrows() { object o = new object(); WeakDictionary <object, object> dict = new WeakDictionary <object, object>(); dict.Add("foo1", o); dict.Add("foo1", o); }
public void CanRemoveAnObjectThatWasAlreadyAdded() { object o = new object(); WeakDictionary <object, object> dict = new WeakDictionary <object, object>(); dict.Add("foo", o); dict.Remove("foo"); object unused = dict["foo"]; }
public void Indexer_NotFound() { Assert.Throws<KeyNotFoundException>(() => { var dictionary = new WeakDictionary<object, object>(); object value = dictionary[new Object()]; } ); }
public object AddOrUpdate(WeakDictionary <int, object> d, int k, object addValue, Func <int, object, object> updateValueFactory) { return (d.AddOrUpdate( k, addValue, (kp1, v) => updateValueFactory(kp1, v) ) ); }
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())); }
public void Indexer_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 = dictionary[k1]; Assert.Equal(true, Object.ReferenceEquals(v1, v2)); Assert.Equal(true, dictionary.Contains(k1)); }
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 TestRemoveDeadItem() { WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(comparer, 5); for (int i = 0; i < 5; i++) { AddAnItem(weakDict, i); } // Force gc to collect dead items GC.Collect(); if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded) { Assert.AreEqual(5, weakDict.Count); // Since the referesh interval is 5, so when adding the sixth item, it should clear the 5 dead items first. weakDict.RemoveCollectedEntries(); Assert.AreEqual(0, weakDict.Count); } }
public void TestBasicOps() { WeakDictionary<string, string> wd = new WeakDictionary<string, string>(); List<string> list = new List<string>(); for (int i = 0; i < 100; i++) { list.Add(i.ToString()); } foreach (string s in list) { wd.Add("k" + s, "v" + s); } foreach(string key in list) { Assert.AreEqual(wd["k"+key],"v"+key); } foreach (string key in list) { wd.Remove("k"+key); } Assert.AreEqual(0,wd.Count); foreach (string s in list) { wd.Add("k" + s, "v" + s); } foreach (string key in wd.Keys) { Assert.True(list.Contains(key.Substring(1))); } foreach(KeyValuePair<string,string> kv in wd) { Assert.True(list.Contains(kv.Key.Substring(1))); Assert.AreEqual(kv.Key.Substring(1), kv.Value.Substring(1)); } }
public void TestAddANullKeyThrowsException() { WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5); Action testAction = () => { weakDict.Add(null, 10); }; testAction.ShouldThrow<ArgumentNullException>(); }
public void TestRemoveDeadItemWhenAddMoreThanCurrentRefreshIntervalItems() { WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5); for (int i = 0; i < 4; i++) { AddAnItem(weakDict, i); } // Force gc to collect dead items GC.Collect(); if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded) { var key1 = new KeyObject(11); weakDict.Add(key1, 11); var key2 = new KeyObject(12); // Weak dictionary will remove dead items during this adding operation. // Then the currentRefreshInterval will be 1(still alive)+5=6. weakDict.Add(key2, 12); Assert.AreEqual(2, weakDict.Count); for (int i = 0; i < 3; i++) { AddAnItem(weakDict, i); } // Force gc to collect dead items GC.Collect(); if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded) { // Add the six item to dictionary. var key6 = new KeyObject(16); // Weak dictionary will not clean dead entities. weakDict.Add(key6, 16); Assert.AreEqual(6, weakDict.Count); var key14 = new KeyObject(114); // Weak dictionary will remove dead items during this adding operation. // Then the currentRefreshInterval will be 3(still alive)+5=8. weakDict.Add(key14, 114); Assert.AreEqual(4, weakDict.Count); } } }
private void AddAnItem(WeakDictionary<KeyObject, int> dict, int id) { KeyObject key = new KeyObject(id); dict.Add(key, rand.Next()); }
public void EqualityComparer() { string k1 = String.Concat("ke", "y"); object v1 = new Object(); var dictionary = new WeakDictionary<string, object>(); dictionary[k1] = v1; // Now look for a different but equatable key // Don't create it with a literal or the compiler will intern it! string k2 = String.Concat("k", "ey"); Assert.Equal(false, Object.ReferenceEquals(k1, k2)); object v2 = dictionary[k2]; Assert.Equal(true, Object.ReferenceEquals(v1, v2)); }
public void TestRemoveDeadItemWhenAddMoreThanRefreshIntervalItems() { WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5); for (int i = 0; i < 5; i++) { AddAnItem(weakDict, i); } // Force gc to collect dead items GC.Collect(); if (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded) { var key = new KeyObject(6); weakDict.Add(key, 6); // The countLimit after the first clean is 6 now. Assert.AreEqual(1, weakDict.Count); } }
static EventDispatcher() { _eventObjDict = new WeakDictionary<object, Dictionary<string, EventObject>>(); _listenerDict = new WeakDictionary<object, List<EventObject>>(); }
private void AddTupleObject(WeakDictionary<object, int> dict, int id) { KeyObject key = new KeyObject(id); var tuple = new Tuple<object, MemberInfo>(key, this.memberInfo); dict.Add(tuple, rand.Next()); }
public void Awake() { DontDestroyOnLoad(this); PossessedCharacterViewID = uLink.NetworkViewID.unassigned; LastGUIDebugPositions = new WeakDictionary<PlayerScript, Vector2>(); // Ladies and gentlemen, the great and powerful Unity wasMine = networkView.isMine; if (networkView.isMine) { Name = PlayerPrefs.GetString("username", "Anonymous"); // TODO will obviously send messages to server twice if there are two local players, fix Relay.Instance.MessageLog.OnMessageEntered += ReceiveMessageEntered; Relay.Instance.MessageLog.OnCommandEntered += ReceiveCommandEntered; } }
internal async Task<Stream> OpenStreamAsync(bool synchronous, bool skipCache = false, bool linger = true) { var url = new LazyUri(Url); await Utils.CheckLocalFileAccessAsync(url); var mgr = this.manager; Func<long, Task<HttpResponseMessage>> createStream = null; #if !STANDALONE && DESKTOP if (Caching.AzureApi != null && (mgr == null || !mgr.IsAlive) && !skipCache) { var container = Caching.GetAzureContainer(url); HashSet<string> files = null; if (synchronous) { ObjectManager.SynchronizationContext.Send(async () => { files = await Caching.GetAzureCachedFiles(container); }); } else { await ObjectManager.SynchronizationContext.SendAsync(async () => { files = await Caching.GetAzureCachedFiles(container); }); } var name = Caching.GetFileCachePath(url); if (files.Contains(name)) { createStream = offset => Caching.GetAzureResponseAsync(container, name, offset, this); } } else #endif if ( #if !STANDALONE && DESKTOP Caching.AzureApi == null && #endif !skipCache) { #if DESKTOP var cache = Caching.GetFileCachePath(url); if (File.Exists(cache)) { var str = new FileStream(cache, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); if (str.Length == 0) { var errfile = Path.ChangeExtension(cache, ".err"); if (File.Exists(errfile)) { str.Dispose(); var errlines = File.ReadAllText(errfile); return new MediaStream(MediaStream.ExceptionFromCachedResponse(errlines), this); } } Sanity.AssertFastReadByte(str); return str; } #endif } lock (this) { if (manager == null) manager = new MediaStreamManager(createStream ?? GetResponseAsync, true); var stream = manager.TryCreateStream(this, 0, linger); if (stream == null) { manager = new MediaStreamManager(createStream ?? GetResponseAsync, true); stream = manager.TryCreateStream(this, 0, linger); Sanity.Assert(stream != null); } Sanity.AssertFastReadByte(stream); return stream; } }
public void ExplicitScavenge() { object k1 = new Object(); object v1 = new Object(); var dictionary = new WeakDictionary<object, object>(); dictionary[k1] = v1; Assert.Equal(1, dictionary.Count); k1 = null; GC.Collect(); dictionary.Scavenge(); Assert.Equal(0, dictionary.Count); }
public void ScavengeOnGrow() { var dictionary = new WeakDictionary<object, object>(); for (int i = 0; i < 100; i++) { dictionary[new Object()] = new Object(); // Randomly collect some if (i == 15) { GC.Collect(); } } // We should have scavenged at least once Console.WriteLine("Count {0}", dictionary.Count); Assert.Equal(true, dictionary.Count < 100); // Finish with explicit scavenge int count1 = dictionary.Count; int removed = dictionary.Scavenge(); int count2 = dictionary.Count; Console.WriteLine("Removed {0}", removed); Assert.Equal(removed, count1 - count2); }
public void ValuesCollectable() { string k1 = new string('k', 1000000); string v1 = new string('v', 1000000); // Each character is 2 bytes, so about 4MB of this should be the strings long memory1 = GC.GetTotalMemory(true); var dictionary = new WeakDictionary<string, string>(); dictionary[k1] = v1; v1 = null; long memory2 = GC.GetTotalMemory(true); // Value collected, sould be about 2MB less long difference = memory1 - memory2; Console.WriteLine("Start {0}, end {1}, diff {2}", memory1, memory2, difference); Assert.Equal(true, difference > 1500000); // 2MB minus big noise allowance // This line is VERY important, as it keeps the GC from being too smart and collecting // the dictionary and its large strings because we never use them again. GC.KeepAlive(dictionary); }
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 void ContainsRemovesDeadValue() { Console.WriteLine("Fixed contains test .."); 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(); Assert.Equal(false, dictionary.Contains(k)); }
public void TestAddSameKeyThrowsException() { WeakDictionary<KeyObject, int> weakDict = new WeakDictionary<KeyObject, int>(this.comparer, 5); KeyObject key = new KeyObject(10); weakDict.Add(key, 10); Action testAction = () => { weakDict.Add(key, 10); }; testAction.ShouldThrow<ArgumentException>(); }
public void Indexer_NotFound() { var dictionary = new WeakDictionary<object, object>(); object value = dictionary[new Object()]; }
private WeakDictionary<object, int> CreateDict(out List<KeyObject> keys) { WeakDictionary<object, int> weakDict = new WeakDictionary<object, int>(this.comparer, refreshInterval: 5); keys = new List<KeyObject>(); for (int i = 0; i < 10; i++) { KeyObject key = new KeyObject(i); keys.Add(key); weakDict.Add(key, i); } return weakDict; }
public void IndexerRemovesDeadValue() { object k = new Object(); object v = new Object(); var dictionary = new WeakDictionary<object, object>(); dictionary[k] = v; v = null; GC.Collect(); object value = dictionary[k]; // throws }
public void IndexerRemovesDeadValue() { object k = new Object(); object v = new Object(); var dictionary = new WeakDictionary<object, object>(); dictionary[k] = v; v = null; GC.Collect(); Assert.Throws<KeyNotFoundException>(() => { object value = dictionary[k]; } ); }
public void TestAddDiffTupleForSameObjectThrowsException() { WeakDictionary<object, int> weakDict = new WeakDictionary<object, int>(this.comparer, 5); var key = new Tuple<object, MemberInfo>(new KeyObject(10), this.memberInfo); weakDict.Add(key, 10); var key2 = new Tuple<object, MemberInfo>(key.Item1, this.memberInfo); Action testAction = () => { weakDict.Add(key2, 10); }; testAction.ShouldThrow<ArgumentException>(); }