本文整理汇总了C#中ConditionalWeakTable.TryGetValue方法的典型用法代码示例。如果您正苦于以下问题:C# ConditionalWeakTable.TryGetValue方法的具体用法?C# ConditionalWeakTable.TryGetValue怎么用?C# ConditionalWeakTable.TryGetValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConditionalWeakTable
的用法示例。
在下文中一共展示了ConditionalWeakTable.TryGetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetIndexAsync
private static async Task<SyntaxTreeIndex> GetIndexAsync(
Document document,
ConditionalWeakTable<Document, SyntaxTreeIndex> cache,
Func<Document, CancellationToken, Task<SyntaxTreeIndex>> generator,
CancellationToken cancellationToken)
{
if (cache.TryGetValue(document, out var info))
{
return info;
}
info = await generator(document, cancellationToken).ConfigureAwait(false);
if (info != null)
{
return cache.GetValue(document, _ => info);
}
// alright, we don't have cached information, re-calculate them here.
var data = await CreateInfoAsync(document, cancellationToken).ConfigureAwait(false);
// okay, persist this info
await data.SaveAsync(document, cancellationToken).ConfigureAwait(false);
return cache.GetValue(document, _ => data);
}
示例2: WeakKey
private static void WeakKey()
{
var people = new[]
{
new Person {Id = 1, Name = "Jurian Naul" },
new Person {Id = 2, Name = "Thomas Bent" },
new Person {Id = 3, Name = "Ellen Carson" },
new Person {Id = 4, Name = "Katrina Lauran" },
new Person {Id = 5, Name = "Monica Ausbach" },
};
var locations = new ConditionalWeakTable<Person, string>();
locations.Add(people[0], "Shinon");
locations.Add(people[1], "Lance");
locations.Add(people[2], "Pidona");
locations.Add(people[3], "Loanne");
locations.Add(people[4], "Loanne");
foreach (var p in people)
{
string location;
if (locations.TryGetValue(p, out location))
Console.WriteLine(p.Name + " at " + location);
}
}
示例3: Should_release_value_when_there_are_no_more_references
public void Should_release_value_when_there_are_no_more_references()
{
var table = new ConditionalWeakTable<TypeWithStrongReferenceThroughTable, TypeWithWeakReference>();
var strong = new TypeWithStrongReferenceThroughTable();
var weak = new TypeWithWeakReference()
{
WeakReference = new WeakReference(strong)
};
table.Add(strong, weak);
GC.Collect();
TypeWithWeakReference result = null;
Assert.That(table.TryGetValue(strong, out result), Is.True);
Assert.That(result, Is.SameAs(weak));
var weakHandleToStrong = new WeakReference(strong);
strong = null;
GC.Collect();
Assert.That(weakHandleToStrong.IsAlive, Is.False);
}
示例4: TryGetInitialVersions
private bool TryGetInitialVersions(ConditionalWeakTable<ProjectId, Versions> initialVersionMap, Project project, string keyName, out Versions versions)
{
// if we already loaded this, return it.
if (initialVersionMap.TryGetValue(project.Id, out versions))
{
return true;
}
// otherwise, load it
return TryLoadInitialVersions(initialVersionMap, project, keyName, out versions);
}
示例5: InvalidArgs_Throws
public static void InvalidArgs_Throws()
{
var cwt = new ConditionalWeakTable<object, object>();
object ignored;
Assert.Throws<ArgumentNullException>("key", () => cwt.Add(null, new object())); // null key
Assert.Throws<ArgumentNullException>("key", () => cwt.TryGetValue(null, out ignored)); // null key
Assert.Throws<ArgumentNullException>("key", () => cwt.Remove(null)); // null key
Assert.Throws<ArgumentNullException>("createValueCallback", () => cwt.GetValue(new object(), null)); // null delegate
object key = new object();
cwt.Add(key, key);
Assert.Throws<ArgumentException>(null, () => cwt.Add(key, key)); // duplicate key
}
示例6: TestOverrides
// this test ensures that while manipulating keys (through add/remove/lookup
// in the dictionary the overriden GetHashCode(), Equals(), and ==operator do not get invoked.
// Earlier implementation was using these functions virtually so overriding them would result in
// the overridden functions being invoked. But later on Ati changed implementation to use
// Runtime.GetHashCode and Object.ReferenceEquals so this test makes sure that overridden functions never get invoked.
public static void TestOverrides()
{
string[] stringArr = new string[50];
for (int i = 0; i < 50; i++)
{
stringArr[i] = "SomeTestString" + i.ToString();
}
ConditionalWeakTable<string, string> tbl = new ConditionalWeakTable<string, string>();
string str;
for (int i = 0; i < stringArr.Length; i++)
{
tbl.Add(stringArr[i], stringArr[i]);
tbl.TryGetValue(stringArr[i], out str);
tbl.Remove(stringArr[i]);
}
}
示例7: GetValueTest
public static void GetValueTest()
{
ConditionalWeakTable<object, object> cwt = new ConditionalWeakTable<object, object>();
object key = new object();
object obj = null;
object value = cwt.GetValue(key, k => new object());
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal(value, cwt.GetOrCreateValue(key));
WeakReference<object> wrValue = new WeakReference<object>(value, false);
WeakReference<object> wrkey = new WeakReference<object>(key, false);
key = null;
value = null;
GC.Collect();
// key and value must be collected
Assert.False(wrValue.TryGetTarget(out obj));
Assert.False(wrkey.TryGetTarget(out obj));
}
示例8: Add
public static void Add(int numObjects)
{
// Isolated to ensure we drop all references even in debug builds where lifetime is extended by the JIT to the end of the method
Func<int, Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]>> body = count =>
{
object[] keys = Enumerable.Range(0, count).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, count).Select(_ => new object()).ToArray();
var cwt = new ConditionalWeakTable<object, object>();
for (int i = 0; i < count; i++)
{
cwt.Add(keys[i], values[i]);
}
for (int i = 0; i < count; i++)
{
object value;
Assert.True(cwt.TryGetValue(keys[i], out value));
Assert.Same(values[i], value);
Assert.Same(value, cwt.GetOrCreateValue(keys[i]));
Assert.Same(value, cwt.GetValue(keys[i], _ => new object()));
}
return Tuple.Create(cwt, keys.Select(k => new WeakReference(k)).ToArray(), values.Select(v => new WeakReference(v)).ToArray());
};
Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]> result = body(numObjects);
GC.Collect();
Assert.NotNull(result.Item1);
for (int i = 0; i < numObjects; i++)
{
Assert.False(result.Item2[i].IsAlive, $"Expected not to find key #{i}");
Assert.False(result.Item3[i].IsAlive, $"Expected not to find value #{i}");
}
}
示例9: GetCachedSemanticModel
private static SemanticModel GetCachedSemanticModel(
ConditionalWeakTable<SyntaxNode, WeakReference<SemanticModel>> nodeMap, SyntaxNode newMember)
{
SemanticModel model;
WeakReference<SemanticModel> cached;
if (!nodeMap.TryGetValue(newMember, out cached) || !cached.TryGetTarget(out model))
{
return null;
}
return model;
}
示例10: OldGenKeysMakeNewGenObjectsReachable
public void OldGenKeysMakeNewGenObjectsReachable ()
{
if (GC.MaxGeneration == 0) /*Boehm doesn't handle ephemerons */
Assert.Ignore ("Not working on Boehm.");
ConditionalWeakTable<object, Val> table = new ConditionalWeakTable<object, Val>();
List<Key> keys = new List<Key>();
//
// This list references all keys for the duration of the program, so none
// should be collected ever.
//
for (int x = 0; x < 1000; x++)
keys.Add (new Key () { Foo = x });
for (int i = 0; i < 1000; ++i) {
// Insert all keys into the ConditionalWeakTable
foreach (var key in keys)
table.Add (key, new Val () { Foo = key.Foo });
// Look up all keys to verify that they are still there
Val val;
foreach (var key in keys)
Assert.IsTrue (table.TryGetValue (key, out val), "#1-" + i + "-k-" + key);
// Remove all keys from the ConditionalWeakTable
foreach (var key in keys)
Assert.IsTrue (table.Remove (key), "#2-" + i + "-k-" + key);
}
}
示例11: Clear_AllValuesRemoved
public static void Clear_AllValuesRemoved(int numObjects)
{
var cwt = new ConditionalWeakTable<object, object>();
MethodInfo clear = cwt.GetType().GetMethod("Clear", BindingFlags.NonPublic | BindingFlags.Instance);
if (clear == null)
{
// Couldn't access the Clear method; skip the test.
return;
}
object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
for (int iter = 0; iter < 2; iter++)
{
// Add the objects
for (int i = 0; i < numObjects; i++)
{
cwt.Add(keys[i], values[i]);
Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object()));
}
// Clear the table
clear.Invoke(cwt, null);
// Verify the objects are removed
for (int i = 0; i < numObjects; i++)
{
object ignored;
Assert.False(cwt.TryGetValue(keys[i], out ignored));
}
// Do it a couple of times, to make sure the table is still usable after a clear.
}
}
示例12: TryGetValue
public void TryGetValue () {
var cwt = new ConditionalWeakTable <object,object> ();
object res;
object c = new Key ();
cwt.Add (c, "foo");
try {
cwt.TryGetValue (null, out res);
Assert.Fail ("#0");
} catch (ArgumentNullException) {}
Assert.IsFalse (cwt.TryGetValue ("foo", out res), "#1");
Assert.IsTrue (cwt.TryGetValue (c, out res), "#2");
Assert.AreEqual ("foo", res, "#3");
}
示例13: AddHandlerToCWT
// add the handler to the CWT - this keeps the handler alive throughout
// the lifetime of the target, without prolonging the lifetime of
// the target
void AddHandlerToCWT(Delegate handler, ConditionalWeakTable<object, object> cwt)
{
object value;
object target = handler.Target;
if (target == null)
target = StaticSource;
if (!cwt.TryGetValue(target, out value))
{
// 99% case - the target only listens once
cwt.Add(target, handler);
}
else
{
// 1% case - the target listens multiple times
// we store the delegates in a list
List<Delegate> list = value as List<Delegate>;
if (list == null)
{
// lazily allocate the list, and add the old handler
Delegate oldHandler = value as Delegate;
list = new List<Delegate>();
list.Add(oldHandler);
// install the list as the CWT value
cwt.Remove(target);
cwt.Add(target, list);
}
// add the new handler to the list
list.Add(handler);
}
}
示例14: Reachability
public void Reachability () {
var cwt = new ConditionalWeakTable <object,object> ();
List<object> keepAlive;
List<WeakReference> keys;
FillStuff (cwt, out keepAlive, out keys);
GC.Collect ();
Assert.IsTrue (keys [0].IsAlive, "r0");
Assert.IsFalse (keys [1].IsAlive, "r1");
Assert.IsTrue (keys [2].IsAlive, "r2");
object res;
Assert.IsTrue (cwt.TryGetValue (keepAlive [0], out res), "ka0");
Assert.IsTrue (res is Link, "ka1");
Link link = res as Link;
Assert.IsTrue (cwt.TryGetValue (link.obj, out res), "ka2");
Assert.AreEqual ("str0", res, "ka3");
}
示例15: GetInfoTable
private static ConditionalWeakTable<DocumentId, SyntaxTreeIndex> GetInfoTable(
BranchId branchId,
Workspace workspace,
ConditionalWeakTable<BranchId, ConditionalWeakTable<DocumentId, SyntaxTreeIndex>> cache)
{
return cache.GetValue(branchId, id =>
{
if (id == workspace.PrimaryBranchId)
{
workspace.DocumentClosed += (sender, e) =>
{
if (!e.Document.IsFromPrimaryBranch())
{
return;
}
if (cache.TryGetValue(e.Document.Project.Solution.BranchId, out var infoTable))
{
// remove closed document from primary branch from live cache.
infoTable.Remove(e.Document.Id);
}
};
}
return new ConditionalWeakTable<DocumentId, SyntaxTreeIndex>();
});
}