本文整理汇总了C#中ConcurrentDictionary.GetOrAdd方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentDictionary.GetOrAdd方法的具体用法?C# ConcurrentDictionary.GetOrAdd怎么用?C# ConcurrentDictionary.GetOrAdd使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentDictionary
的用法示例。
在下文中一共展示了ConcurrentDictionary.GetOrAdd方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Unsafe_ConcurrentDictionary_GetOrAdd_CallsValueFactoryMultipleTimes
public void Unsafe_ConcurrentDictionary_GetOrAdd_CallsValueFactoryMultipleTimes()
{
var dictionary = new ConcurrentDictionary<string, string>();
string thread1Message = null, thread2Message = null;
var thread1 = new Thread(() =>
dictionary.GetOrAdd("key", _ =>
{
Thread.SpinWait(10000);
thread1Message = "thread 1";
return thread1Message;
}));
var thread2 = new Thread(() =>
dictionary.GetOrAdd("key", _ =>
{
Thread.SpinWait(10000);
thread2Message = "thread 2";
return thread2Message;
}));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Assert.That(thread1Message, Is.EqualTo("thread 1"));
Assert.That(thread2Message, Is.EqualTo("thread 2"));
}
示例2: NizzleName
public void NizzleName()
{
var dictionary = new ConcurrentDictionary<string, string>();
ThreadPool.QueueUserWorkItem(__ =>
{
dictionary.GetOrAdd("bimse", _ =>
{
Console.WriteLine("waiting");
Thread.Sleep(1000);
Console.WriteLine("done");
return "hej";
});
});
ThreadPool.QueueUserWorkItem(__ =>
{
dictionary.GetOrAdd("bimse", _ =>
{
Console.WriteLine("waiting");
Thread.Sleep(1000);
Console.WriteLine("done");
return "hej";
});
});
Thread.Sleep(3000);
}
示例3: Test_ConcurrentDictionary_04
public static void Test_ConcurrentDictionary_04()
{
ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
dictionary.GetOrAdd(1, "toto1");
dictionary.GetOrAdd(1, "toto2");
dictionary.GetOrAdd(2, "tata");
dictionary.GetOrAdd(3, "tutu");
dictionary.GetOrAdd(4, "titi");
foreach (KeyValuePair<int, string> value in dictionary)
{
Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
if (value.Key == 2)
{
Trace.Write("TryRemove key 2");
string s;
if (dictionary.TryRemove(2, out s))
Trace.Write(" ok");
else
Trace.Write(" error");
Trace.WriteLine();
}
}
Trace.WriteLine("read again");
foreach (KeyValuePair<int, string> value in dictionary)
{
Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
}
}
示例4: Test_ConcurrentDictionary_01
public static void Test_ConcurrentDictionary_01()
{
ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
dictionary.GetOrAdd(1, "toto1");
dictionary.GetOrAdd(1, "toto2");
dictionary.GetOrAdd(2, "tata");
dictionary.GetOrAdd(3, "tutu");
dictionary.GetOrAdd(4, "titi");
foreach (KeyValuePair<int, string> value in dictionary)
{
Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
}
}
示例5: Game
public Game()
{
if (Random == null)
{
Random = new Random();
}
Id = _MAXID++;
Elevators = new ConcurrentDictionary<int, Elevator>();
// dirty filthy hacks
var evenElevators = Random.Next(NUMBER_OF_FLOORS);
var oddElevators = Random.Next(NUMBER_OF_FLOORS);
for (int i = 0; i < _NUMBER_OF_ELEVATORS; i++)
{
Elevators.GetOrAdd(i, new Elevator(){Id = i, Floor = (i % 2 == 0) ? evenElevators : oddElevators, Meeples = new List<Meeple>()});
}
Floors = new ConcurrentDictionary<int, Floor>();
for (int i = 0; i < NUMBER_OF_FLOORS; i++)
{
Floors.GetOrAdd(i, new Floor() {Meeples = new List<Meeple>(), Number = i});
}
AddMeepleToFloors();
Turn = 0;
Running = false;
_started = false;
_gameLoop = new HighFrequencyTimer(60, this.Update);
}
示例6: GetContext
static ThreadContext GetContext(ConcurrentDictionary<int, ThreadContext> nodes) {
return nodes.GetOrAdd(Thread.CurrentThread.ManagedThreadId, _ => {
var tc = new ThreadContext();
tc.Root = tc.Clock = tc.Chain = tc.Focus = new Node(tc);
return tc;
});
}
示例7: Test13
private static void Test13()
{
ConcurrentDictionary<AggregationKey, List<string>> dic = new ConcurrentDictionary<AggregationKey, List<string>>();
DateTime d1 = DateTime.Now.RoundTo(TimeSpan.FromSeconds(1));
DateTime d2 = d1;
DateTime d3 = d2.AddSeconds(5);
Dictionary<string, string> dic1 = new Dictionary<string, string>();
dic1["e1"] = "v1";
dic1["e2"] = "v2";
dic1["e3"] = "v3";
dic1["e4"] = "v4";
Dictionary<string, string> dic2 = new Dictionary<string, string>();
dic2["e1"] = "v1";
dic2["e2"] = "v2";
dic2["e3"] = "v3";
dic2["e4"] = "v5";
Dictionary<string, string> dic3 = new Dictionary<string, string>();
dic3["e1"] = "v1";
dic3["e2"] = "v2";
dic3["e3"] = "v3";
dic3["e4"] = "v4";
AggregationKey ak1 = new AggregationKey(d1,dic1);
AggregationKey ak2 = new AggregationKey(d2,dic2);
AggregationKey ak3 = new AggregationKey(d3,dic3);
dic.GetOrAdd(ak1,new List<string>()).Add("f1");
dic.GetOrAdd(ak2,new List<string>()).Add("f2");
dic.GetOrAdd(ak3,new List<string>()).Add("f3");
Console.ReadLine();
}
示例8: Weave
public void Weave()
{
var weaverCache = new ConcurrentDictionary<string, AspectWeaver>();
foreach (var type in _module.Types)
{
foreach (var method in type.Methods)
{
var aspects = new List<AspectWeaver>();
foreach (var attr in method.CustomAttributes)
{
var attrName = attr.AttributeType.FullName;
if (attrName.EndsWith(Resources.AspectAttribute))
{
Debug.WriteLine("Found Aspect {0} on {1}.{2}", attrName, type.Name, method.Name);
var weaver = weaverCache.GetOrAdd(attrName, _ => new AspectWeaver(attr.AttributeType));
aspects.Add(weaver);
}
}
aspects.Reverse();
foreach (var weaver in aspects)
{
weaver.Weave(method);
}
}
}
}
示例9: Foo2
private void Foo2()
{
var concurentDictionary = new ConcurrentDictionary<int, int>();
var w = new ManualResetEvent(false);
int timedCalled = 0;
var threads = new List<Thread>();
Lazy<int> lazy = new Lazy<int>(() => { Interlocked.Increment(ref timedCalled); return 1; });
for (int i = 0; i < Environment.ProcessorCount; i++)
{
threads.Add(new Thread(() =>
{
w.WaitOne();
concurentDictionary.GetOrAdd(1, i1 =>
{
return lazy.Value;
});
}));
threads.Last().Start();
}
w.Set();//release all threads to start at the same time
Thread.Sleep(100);
Console.WriteLine(timedCalled);// output is 1
}
示例10: Main
public static void Main(string[] args)
{
// When working with a ConcurrentDictionary you have methods that can atomically add, get, and update items.
// An atomic operation means that it will be started and finished as a single step without other threads interfering.
// TryUpdate checks to see whether the current value is equal to the existing value before updating it.
// AddOrUpdate makes sure an item is added if it’s not there, and updated to a new value if it is.
// GetOrAdd gets the current value of an item if it’s available; if not, it adds the new value by using a factory method.
var dictionary = new ConcurrentDictionary<string, int>();
if (dictionary.TryAdd("k1", 42))
{
Console.WriteLine("Added");
}
if (dictionary.TryUpdate("k1", 21, 42))
{
Console.WriteLine("42 updated to 21");
}
dictionary["k1"] = 42; // Overwrite unconditionally
int r1 = dictionary.AddOrUpdate("k1", 3, (s, i) => i * 2);
int r2 = dictionary.GetOrAdd("k2", 3);
Console.ReadLine();
}
示例11: GetSessionStateBehavior
private static SessionStateBehavior? GetSessionStateBehavior(WebPageExecutingBase page, ConcurrentDictionary<Type, SessionStateBehavior?> cache)
{
return cache.GetOrAdd(page.GetType(), type =>
{
SessionStateBehavior sessionStateBehavior = SessionStateBehavior.Default;
var attributes = (RazorDirectiveAttribute[])type.GetCustomAttributes(typeof(RazorDirectiveAttribute), inherit: false);
var directiveAttributes = attributes.Where(attr => StringComparer.OrdinalIgnoreCase.Equals("sessionstate", attr.Name))
.ToList();
if (!directiveAttributes.Any())
{
return null;
}
if (directiveAttributes.Count > 1)
{
throw new InvalidOperationException(WebPageResources.SessionState_TooManyValues);
}
var directiveAttribute = directiveAttributes[0];
if (!Enum.TryParse<SessionStateBehavior>(directiveAttribute.Value, ignoreCase: true, result: out sessionStateBehavior))
{
var values = Enum.GetValues(typeof(SessionStateBehavior)).Cast<SessionStateBehavior>().Select(s => s.ToString());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, WebPageResources.SessionState_InvalidValue,
directiveAttribute.Value, page.VirtualPath, String.Join(", ", values)));
}
return sessionStateBehavior;
});
}
示例12: MainMethod
public void MainMethod()
{
Console.WriteLine("Concurrent Dictionary Run implementation");
ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
if(dictionary.TryAdd("k1",10))
{
Console.WriteLine("Added Key k1");
}
if(dictionary.TryUpdate("k1",19,10))
{
Console.WriteLine("Updated Key k1");
}
if (dictionary.TryUpdate("k1", 19, 10))
{
Console.WriteLine("Updated Key k1");
}
else
Console.WriteLine("Failed to Update");
dictionary["k1"] = 16;
int r1 = dictionary.AddOrUpdate("k1", 2, (s, i) => i * 2);
Console.WriteLine(r1);
int r3 = dictionary.AddOrUpdate("k3", 2, (s, i) => i * 2);
Console.WriteLine(r3);
int r2 = dictionary.GetOrAdd("k2", 4);
Console.WriteLine(r2);
}
示例13: Main
public static void Main()
{
var stock = new ConcurrentDictionary<string, int>();
stock.TryAdd("jDays", 4);
stock.TryAdd("technologyhour", 3);
Console.WriteLine("No. of shirts in stock = {0}", stock.Count);
var success = stock.TryAdd("pluralsight", 6);
Console.WriteLine("Added succeeded? " + success);
success = stock.TryAdd("pluralsight", 6);
Console.WriteLine("Added succeeded? " + success);
stock["buddhistgeeks"] = 5;
//stock["pluralsight"]++; <-- not thread safe two instructions
var psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
Console.WriteLine("pluralsight new value = {0}", psStock);
Console.WriteLine("stock[pluralsight] = {0}", stock.GetOrAdd("pluralsight", 0));
int jDaysValue;
success= stock.TryRemove("jDays", out jDaysValue);
if (success) Console.WriteLine("Value removed was: " + jDaysValue);
Console.WriteLine("\r\nEnumerating:");
foreach (var keyValuePair in stock)
{
Console.WriteLine("{0}: {1}", keyValuePair.Key, keyValuePair.Value);
}
}
示例14: Main
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// Создание объекта ConcurrentDictionary
var dict = new ConcurrentDictionary<String, int>();
// Попытка добавить элемент [k1;42]
if (dict.TryAdd("k1", 42))
Console.WriteLine("Added");
// Обновление значения элемента [k1;42] на [k1;21]
if (dict.TryUpdate("k1", 21, 42))
Console.WriteLine("42 updated to 21");
dict["k1"] = 42; // безоговорочная перезапись значения k1
// Добавление или обновление элемента (если существует)
int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2);
// Получение значения k2 (если его не существует - добавление в коллекцию
int r2 = dict.GetOrAdd("k2", 3);
Console.WriteLine(r1);
Console.WriteLine(r2);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
示例15: Profile
private static void Profile()
{
Console.WriteLine("64bit: " + Environment.Is64BitProcess);
var dict = new ConcurrentDictionary<string,string>();
for (int i = 0; i < 0x5fffff; i++)
{
dict.GetOrAdd("1", (input) => "2");
}
}