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


C# ConcurrentDictionary.TryUpdate方法代码示例

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


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

示例1: 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);
        }
开发者ID:mayankaggarwal,项目名称:MyConcepts,代码行数:30,代码来源:Concept18.cs

示例2: Main

        static void Main(string[] args)
        {
            var mySymbols = new Symbols();
            ConcurrentDictionary<string, int> original = new ConcurrentDictionary<string, int>();
            ConcurrentDictionary<string, int> copy = new ConcurrentDictionary<string, int>();

            var rnd = new Random();
            foreach (var symbol in mySymbols.All.OrderBy(s => s))
            {

                original.TryAdd(symbol, rnd.Next(0, 1000));
                copy.TryAdd(symbol, 0);
            }

            int i = 0;

            Parallel.ForEach(original, orig =>
            {
                Thread.Sleep(orig.Value);

                lock (lockObj)
                {
                    copy.TryUpdate(orig.Key, orig.Value, 0);
                    Console.WriteLine("{0} :: {1}", orig.Key, i);
                    Interlocked.Increment(ref i);
                }
            });

            int j = 0;
        }
开发者ID:briask,项目名称:PlayTime,代码行数:30,代码来源:Program.cs

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

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

示例5: Main

        static void Main()
        {
            // New instance.
            var con = new ConcurrentDictionary<string, int>();
            con.TryAdd("cat", 1);
            con.TryAdd("dog", 2);

            // Try to update if value is 4 (this fails).
            con.TryUpdate("cat", 200, 4);

            // Try to update if value is 1 (this works).
            con.TryUpdate("cat", 100, 1);

            // Write new value.
            Console.WriteLine(con["cat"]);
            Console.ReadKey();
        }
开发者ID:vulcanlee,项目名称:Parallel_Asynchronous_Sample,代码行数:17,代码来源:Program.cs

示例6: PopulateDictParallel

 static void PopulateDictParallel(ConcurrentDictionary<int, int> dict, int dictSize)
 {
     Parallel.For(0, dictSize, i => dict.TryAdd(i, 0));
     Parallel.For(0, dictSize, i =>
     {
         var done = dict.TryUpdate(i, 1, 0);
         if (!done) throw new Exception("Error updating. Old value was " + dict[i]);
         Worker.DoSomethingTimeConsuming();
     });
 }
开发者ID:kenwilcox,项目名称:ConcurrentCollections,代码行数:10,代码来源:ParallelBenchmark.cs

示例7: Run

 public void Run()
 {
     var dict = new ConcurrentDictionary<string, int>();
     if (dict.TryAdd("k1", 42))
     {
         Console.WriteLine("Added");
     }
     if (dict.TryUpdate("k1", 21, 42))
     {
         Console.WriteLine("42 updated to 21");
     }
     dict["k1"] = 42; // Overwrite unconditionally
     int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2);
     int r2 = dict.GetOrAdd("k2", 3);
 }
开发者ID:vikramadhav,项目名称:Certification_70-483,代码行数:15,代码来源:Listing_1_34.cs

示例8: Main

        private static void Main()
        {
            var dictionary = new ConcurrentDictionary<string, int>();
            if (dictionary.TryAdd("k1", 42)) {
                Console.WriteLine("Added 42");
            }

            // Overwrite conditionally
            if (dictionary.TryUpdate("k1", 21, 42)) {
                Console.WriteLine("42 updated to 21");
            }
            //Overwrite unconditionally
            dictionary["k1"] = 42;

            var r1 = dictionary.AddOrUpdate("k1", 3, (s, i) => i * 2);
            var r2 = dictionary.GetOrAdd("k2", 3);

            Console.ReadLine();
        }
开发者ID:DriesPeeters,项目名称:examprep-70_483,代码行数:19,代码来源:Program.cs

示例9: Run

        public override void Run()
        {
            ConcurrentDictionary<int, string> d = new ConcurrentDictionary<int, string>(CONCURRENCY_LEVEL, ARRAY_SIZE);

            for (int i = 0; i < 1000000; i++)
            {
                d.TryAdd(i, "abc");
            }

            string s = string.Empty;

            __sw.Reset();
            __sw.Start();

            Parallel.For(0, 1000000, i => d.TryUpdate(i, s, "a"));

            __sw.Stop();

            Console.WriteLine("Parallel Update ConcurrentDictionary: {0}", __sw.ElapsedTicks);
        }
开发者ID:serkanberksoy,项目名称:DCache,代码行数:20,代码来源:ParallelUpdate.cs

示例10: Main

        static void Main(string[] args)
        {
            ConcurrentStack<int> stack = new ConcurrentStack<int>();
            stack.Push(67);

            int result;
            if (stack.TryPop(out result))
                Console.WriteLine("Popped: {0}", result);
            stack.PushRange(new int[] { 1, 2, 3 });
            int[] values = new int[2];
            stack.TryPopRange(values);
            foreach (int i in values)
                Console.WriteLine(i);

            Console.WriteLine("\n\n----------------------------------------------------------------------\n\n");
            Console.ReadLine();

            var dict = new ConcurrentDictionary<string, int>();
            if (dict.TryAdd("ERHAN",26))
            {
                Console.WriteLine("Added");
            }
            if (dict.TryUpdate("ERHAN", 30, 26))
            {
                Console.WriteLine("26 updated to 30");
            }

            dict["ERHAN"] = 32; // Overwrite unconditionally

            Console.WriteLine("----------------------------------------------------------------------");
            Console.ReadLine();

            int r = dict.AddOrUpdate("ERHAN", 35, (S, I) => I * 2);
            Console.WriteLine(r);
            int r2 = dict.GetOrAdd("ERHAN", 37);

            Console.WriteLine("----------------------------------------------------------------------");
            Console.ReadLine();
        }
开发者ID:ErhanGDC,项目名称:MyWorks,代码行数:39,代码来源:Program.cs

示例11: AddOrIncrementValue

 private static void AddOrIncrementValue(string key, ConcurrentDictionary<string, int> dict)
 {
   bool success = false;
   while (!success)
   {
     int value;
     if (dict.TryGetValue(key, out value))
     {
       if (dict.TryUpdate(key, value + 1, value))
       {
         success = true;
       }
     }
     else
     {
       if (dict.TryAdd(key, 1))
       {
         success = true;
       }
     }
   }
 }
开发者ID:Ricky-Hao,项目名称:ProCSharp,代码行数:22,代码来源:Program.cs

示例12: Run

		public void  Run ()
		{
			var dict = new ConcurrentDictionary<string, int> (StringComparer.InvariantCultureIgnoreCase);

			Action adder = () => {

				for (var x = 0; x < 10; x++) {
					dict.TryAdd (x.ToString (), x);
				}

				for (var x = 0; x < 10; x++) {
					dict.TryUpdate (x.ToString (), x * x, x);
				}

			};
		
			var t1 = Task.Run (adder);
			var t2 = Task.Run (adder);

			Task.WaitAll (t1, t2);

			Result = dict.Values.Sum (x => x);
		}
开发者ID:caloggins,项目名称:DOT-NET-on-Linux,代码行数:23,代码来源:ConcurrentDictionaryExample.cs

示例13: Main

        static void Main(string[] args)
        {
            var dict = new ConcurrentDictionary<string, int>();
            if (dict.TryAdd("k1", 42))
            {
                Console.WriteLine("Added");
            }

            if (dict.TryUpdate("k1", 21, 42))
            {
                Console.WriteLine("42 updated to 21");
            }

            dict["k1"] = 42; // Overwrite unconditinally

            int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2);
            int r2 = dict.GetOrAdd("k2", 3);

            Console.WriteLine("r1: {0}", r1);
            Console.WriteLine("r2: {0}", r2);

            Console.Write("Press a key to exit");
            Console.ReadKey();
        }
开发者ID:jbijoux,项目名称:Exam70_483,代码行数:24,代码来源:Program.cs

示例14: Main

        static void Main(string[] args) {

            // create the bank account instance
            BankAccount account = new BankAccount();

            // create a shared dictionary
            ConcurrentDictionary<object, int> sharedDict
                = new ConcurrentDictionary<object, int>();

            // create tasks to process the list
            Task<int>[] tasks = new Task<int>[10];
            for (int i = 0; i < tasks.Length; i++) {

                // put the initial value into the dictionary
                sharedDict.TryAdd(i, account.Balance);

                // create the new task
                tasks[i] = new Task<int>((keyObj) => {

                    // define variables for use in the loop
                    int currentValue;
                    bool gotValue;

                    // enter a loop for 1000 balance updates
                    for (int j = 0; j < 1000; j++) {
                        // get the current value from the dictionary
                        gotValue = sharedDict.TryGetValue(keyObj, out currentValue);
                        // increment the value and update the dictionary entry
                        sharedDict.TryUpdate(keyObj, currentValue + 1, currentValue);
                    }

                    // define the final result
                    int result;
                    // get our result from the dictionary
                    gotValue = sharedDict.TryGetValue(keyObj, out result);
                    // return the result value if we got one
                    if (gotValue) {
                        return result;
                    } else {
                        // there was no result available - we have encountered a problem
                        throw new Exception(
                            String.Format("No data item available for key {0}", keyObj));
                    }
                }, i);

                // start the new task
                tasks[i].Start();
            }

            // update the balance of the account using the task results
            for (int i = 0; i < tasks.Length; i++) {
                account.Balance += tasks[i].Result;
            }

            // write out the counter value
            Console.WriteLine("Expected value {0}, Balance: {1}",
                10000, account.Balance);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();

        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:63,代码来源:Listing_21.cs

示例15: ConcurrentDictionaryTryAddTest

        public void ConcurrentDictionaryTryAddTest()
        {
            int numFailures = 0; // for bookkeeping 

            // Construct an empty dictionary
            ConcurrentDictionary<int, String> cd = new ConcurrentDictionary<int, string>();

            // This should work 
            if (!cd.TryAdd(1, "one"))
            {
                Console.WriteLine("CD.TryAdd() failed when it should have succeeded");
                numFailures++;
            }

            // This shouldn't work -- key 1 is already in use 
            if (!cd.TryAdd(12, "uno"))
            {
                Console.WriteLine("CD.TryAdd() succeeded when it should have failed");
                numFailures++;
            }

            // Now change the value for key 1 from "one" to "uno" -- should work
            if (!cd.TryUpdate(2, "uno", "one"))
            {
                Console.WriteLine("CD.TryUpdate() failed when it should have succeeded");
                numFailures++;
            }

            // Try to change the value for key 1 from "eine" to "one"  
            //    -- this shouldn't work, because the current value isn't "eine" 
            if (!cd.TryUpdate(1, "one", "eine"))
            {
                Console.WriteLine("CD.TryUpdate() succeeded when it should have failed");
                numFailures++;
            }

            // Remove key/value for key 1.  Should work. 
            string value1;
            if (!cd.TryRemove(1, out value1))
            {
                Console.WriteLine("CD.TryRemove() failed when it should have succeeded");
                numFailures++;
            }

            // Remove key/value for key 1.  Shouldn't work, because I already removed it 
            string value2;
            if (cd.TryRemove(1, out value2))
            {
                Console.WriteLine("CD.TryRemove() succeeded when it should have failed");
                numFailures++;
            }

            // If nothing went wrong, say so 
            if (numFailures == 0) Console.WriteLine("  OK!");
        }
开发者ID:Letractively,项目名称:henoch,代码行数:55,代码来源:ResourceTest.cs


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