当前位置: 首页>>代码示例>>C#>>正文


C# ConditionalWeakTable.TryGetValue方法代码示例

本文整理汇总了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);
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:25,代码来源:SyntaxTreeIndex.cs

示例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);
            }
        }
开发者ID:ufcpp,项目名称:UfcppSample,代码行数:26,代码来源:Program.cs

示例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);
        }
开发者ID:bverburg,项目名称:FakeItEasy,代码行数:26,代码来源:ConditionalWeakTableTests.cs

示例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);
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:11,代码来源:SemanticVersionTrackingService.cs

示例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
        }
开发者ID:saurabh500,项目名称:corefx,代码行数:14,代码来源:ConditionalWeakTableTests.cs

示例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]);
        }
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:testoverrides.cs

示例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));
    }
开发者ID:nblumhardt,项目名称:corefx,代码行数:22,代码来源:ConditionalWeakTable.cs

示例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}");
            }
        }
开发者ID:saurabh500,项目名称:corefx,代码行数:37,代码来源:ConditionalWeakTableTests.cs

示例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;
            }
开发者ID:jerriclynsjohn,项目名称:roslyn,代码行数:12,代码来源:SemanticModelWorkspaceServiceFactory.cs

示例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);
		}
	}
开发者ID:Profit0004,项目名称:mono,代码行数:29,代码来源:ConditionalWeakTableTest.cs

示例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.
            }
        }
开发者ID:chcosta,项目名称:corefx,代码行数:36,代码来源:ConditionalWeakTableTests.cs

示例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");
	}
开发者ID:Profit0004,项目名称:mono,代码行数:16,代码来源:ConditionalWeakTableTest.cs

示例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);
            }
        }
开发者ID:JianwenSun,项目名称:cc,代码行数:36,代码来源:CanExecuteChangedEventManager.cs

示例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");
	}
开发者ID:stabbylambda,项目名称:mono,代码行数:21,代码来源:ConditionalWeakTableTest.cs

示例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>();
            });
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:27,代码来源:SyntaxTreeIndex_Persistence.cs


注:本文中的ConditionalWeakTable.TryGetValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。