本文整理汇总了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);
}
示例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);
}