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


C# ConcurrentDictionary.GetOrAddSafe方法代码示例

本文整理汇总了C#中ConcurrentDictionary.GetOrAddSafe方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.GetOrAddSafe方法的具体用法?C# ConcurrentDictionary.GetOrAddSafe怎么用?C# ConcurrentDictionary.GetOrAddSafe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ConcurrentDictionary的用法示例。


在下文中一共展示了ConcurrentDictionary.GetOrAddSafe方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Safe_ConcurrentDictionary_GetOrAdd_CallsValueFactoryOnlyOnce

        public void Safe_ConcurrentDictionary_GetOrAdd_CallsValueFactoryOnlyOnce()
        {
            var dictionary = new ConcurrentDictionary<string, Lazy<string>>();
            string thread1Message = null, thread2Message = null;

            var thread1 = new Thread(() => 
                dictionary.GetOrAddSafe("key", _ =>
                {
                    Thread.SpinWait(10000);
                    thread1Message = "thread 1";
                    return thread1Message;
                }));

            var thread2 = new Thread(() => 
                dictionary.GetOrAddSafe("key", _ =>
                {
                    Thread.SpinWait(10000);
                    thread2Message = "thread 2";
                    return thread2Message;
                }));

            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();

            bool thread1AndNotThread2 = thread1Message == "thread 1" && thread2Message == null;
            bool thread2AndNotThread1 = thread2Message == "thread 2" && thread1Message == null;

            Assert.IsTrue(thread1AndNotThread2 || thread2AndNotThread1);
        }
开发者ID:yonglehou,项目名称:WcfClientProxyGenerator,代码行数:31,代码来源:DictionaryExtensionsTests.cs

示例2: GetOrAddSafe_OnConcurrentAccess_ReturnsSameInstance

        public async Task GetOrAddSafe_OnConcurrentAccess_ReturnsSameInstance()
        {
            const string key = "key";
            var dictionary = new ConcurrentDictionary<string, Lazy<object>>();

            var valueFactory = new Func<string, object>(k =>
            {
                Thread.Sleep(100);
                return new { };
            });

            var r1 = await Task.Run(() => dictionary.GetOrAddSafe(key, valueFactory));
            var r2 = await Task.Run(() => dictionary.GetOrAddSafe(key, valueFactory));
            Thread.Sleep(10);
            var r3 = await Task.Run(() => dictionary.GetOrAddSafe(key, valueFactory));

            Assert.True(r1 == r2 && r2 == r3);
        }
开发者ID:yonglehou,项目名称:Mjolnir,代码行数:18,代码来源:ConcurrentDictionaryExtensionsTests.cs


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