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


C# ConcurrentDictionary.AddOrUpdate方法代码示例

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


在下文中一共展示了ConcurrentDictionary.AddOrUpdate方法的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: Logger

        static Logger()
        {
            Container = new ConcurrentDictionary<string, List<Message>>();
            Container.AddOrUpdate("error", new List<Message>(), (s, list) => new List<Message>());
            Container.AddOrUpdate("info", new List<Message>(), (s, list) => new List<Message>());
            Container.AddOrUpdate("warning", new List<Message>(), (s, list) => new List<Message>());
            Container.AddOrUpdate("debug", new List<Message>(), (s, list) => new List<Message>());
            Container.AddOrUpdate("fatal", new List<Message>(), (s, list) => new List<Message>());

        }
开发者ID:lifei6671,项目名称:TaskScheduler,代码行数:10,代码来源:Logger.cs

示例3: SetValue

 public void SetValue()
 {
     var Test = new ConcurrentDictionary<string, int>();
     Test.AddOrUpdate("Q", 4, (x, y) => 4);
     Test.AddOrUpdate("Z", 2, (x, y) => 4);
     Test.AddOrUpdate("C", 3, (x, y) => 4);
     Test.AddOrUpdate("A", 1, (x, y) => 4);
     Assert.Equal(4, Test.GetValue("Q"));
     Test.SetValue("Q", 40);
     Assert.Equal(40, Test.GetValue("Q"));
 }
开发者ID:modulexcite,项目名称:Craig-s-Utility-Library,代码行数:11,代码来源:ConcurrentDictionaryExtensions.cs

示例4: Test_ConcurrentDictionary_02

 public static void Test_ConcurrentDictionary_02()
 {
     ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
     // Func<TKey, TValue, TValue> updateValueFactory : Fonction utilisée pour générer une nouvelle valeur pour une clé existante en fonction de la valeur existante de la clé
     dictionary.AddOrUpdate(1, "toto1", (id, text) => "toto1");
     dictionary.AddOrUpdate(1, "toto2", (id, text) => "toto2");
     dictionary.AddOrUpdate(2, "tata", (id, text) => "tata");
     dictionary.AddOrUpdate(3, "tutu", (id, text) => "tutu");
     dictionary.AddOrUpdate(4, "titi", (id, text) => "titi");
     foreach (KeyValuePair<int, string> value in dictionary)
     {
         Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
     }
 }
开发者ID:labeuze,项目名称:source,代码行数:14,代码来源:Test_CollectionsConcurrent.cs

示例5: Queue_WithLowThreadCount_WorksCorrectly

        public void Queue_WithLowThreadCount_WorksCorrectly(int threads, int enqueues, int dequeues)
        {
            //The elements we insert are unique and sentinel value is -1
            int initialValue = -1;
            int currentValue = initialValue;
            ConcurrentDictionary<int, int> table = new ConcurrentDictionary<int, int>();
            Core.Queue.Queue<int> queue = new Core.Queue.Queue<int>(initialValue);

            ThreadBuilder
                .Empty()
                .AddThreads(() =>
                {
                    for (int i = 0; i < enqueues; i++)
                    {
                        int value = Interlocked.Increment(ref currentValue);
                        queue.Enqueue(value);
                    }
                }, threads)
                .AddThreads(() =>
                {
                    for (int i = 0; i < dequeues; i++)
                    {
                        int value = queue.Dequeue();
                        table.AddOrUpdate(value, x => 1, (k, v) => v + 1);
                    }
                }, threads)
                .Start();

            //The sentinel value can be returned more than once if queue is empty at the time of a dequeue
            int expectedDequeues = table.Keys.Count + (table.ContainsKey(initialValue) ? -1 : 0);
            int actualDequeues = table.Count(x => x.Key != initialValue && x.Value == 1);

            Assert.AreEqual(expectedDequeues, actualDequeues);
        }
开发者ID:ionuttamas,项目名称:LockFree,代码行数:34,代码来源:QueueTests.cs

示例6: GetProperty

		private IProperty GetProperty(PropertyInfo propertyInfo, ElasticsearchPropertyAttributeBase attribute)
		{
			var property = _visitor.Visit(propertyInfo, attribute);
			if (property != null)
				return property;

			if (propertyInfo.GetGetMethod().IsStatic)
				return null;

			if (attribute != null)
				property = attribute;
			else
				property = InferProperty(propertyInfo.PropertyType);

			var objectProperty = property as IObjectProperty;
			if (objectProperty != null)
			{
				var type = GetUnderlyingType(propertyInfo.PropertyType);
				var seenTypes = new ConcurrentDictionary<Type, int>(_seenTypes);
				seenTypes.AddOrUpdate(type, 0, (t, i) => ++i);
				var walker = new PropertyWalker(type, _visitor, _maxRecursion, seenTypes);
				objectProperty.Properties = walker.GetProperties(seenTypes, _maxRecursion);
			}

			_visitor.Visit(property, propertyInfo, attribute);

			return property;
		}
开发者ID:jeroenheijmans,项目名称:elasticsearch-net,代码行数:28,代码来源:PropertyWalker.cs

示例7: Get

        public static IDelayDecorator Get(string username, CommandHandler command)
        {
            var userDecorator = UserDecorator.Get(username, command, true);
            var globalDecorator = GlobalDecorator.Get(command);

            if (HybridInstances.ContainsKey(command))
            {
                if (HybridInstances[command].ContainsKey(username))
                    return HybridInstances[command][username];

                var hybridDecorator = new HybridDecorator(userDecorator, globalDecorator);

                HybridInstances[command].AddOrUpdate(username, hybridDecorator, (k, v) => hybridDecorator);

                return hybridDecorator;
            }

            var decorator = new HybridDecorator(userDecorator, globalDecorator);
            var hybrid = new ConcurrentDictionary<string, HybridDecorator>();
            hybrid.AddOrUpdate(username, decorator, (k, v) => decorator);

            HybridInstances.AddOrUpdate(command, hybrid, (k, v) => hybrid);

            return decorator;
        }
开发者ID:Zaharkov,项目名称:TwitchChat,代码行数:25,代码来源:HybridDecorator.cs

示例8: Run

        // Demonstrates:
        //      ConcurrentDictionary<TKey, TValue> ctor(concurrencyLevel, initialCapacity)
        //      ConcurrentDictionary<TKey, TValue>[TKey]
        public static void Run()
        {
            // We know how many items we want to insert into the ConcurrentDictionary.
            // So set the initial capacity to some prime number above that, to ensure that
            // the ConcurrentDictionary does not need to be resized while initializing it.
            int HIGHNUMBER = 64;
            int initialCapacity = 101;

            // The higher the concurrencyLevel, the higher the theoretical number of operations
            // that could be performed concurrently on the ConcurrentDictionary.  However, global
            // operations like resizing the dictionary take longer as the concurrencyLevel rises.
            // For the purposes of this example, we'll compromise at numCores * 2.
            int numProcs = Environment.ProcessorCount;
            int concurrencyLevel = numProcs * 2;

            // Construct the dictionary with the desired concurrencyLevel and initialCapacity
            ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(concurrencyLevel, initialCapacity);

            // Initialize the dictionary
            for (int i = 1; i <= HIGHNUMBER; i++) cd[i] = i * i;

            Console.WriteLine("The square of 23 is {0} (should be {1})", cd[23], 23 * 23);

            // Now iterate through, adding one to the end of the list. Existing items should be updated to be divided by their
            // key  and a new item will be added that is the square of its key.
            for (int i = 1; i <= HIGHNUMBER + 1; i++)
                cd.AddOrUpdate(i, i * i, (k, v) => v / i);

            Console.WriteLine("The square root of 529 is {0} (should be {1})", cd[23], 529 / 23);
            Console.WriteLine("The square of 65 is {0} (should be {1})", cd[HIGHNUMBER + 1], ((HIGHNUMBER + 1) * (HIGHNUMBER + 1)));
        }
开发者ID:killbug2004,项目名称:cosps,代码行数:34,代码来源:CD_Ctor.cs

示例9: ReadFile

        public static ConcurrentDictionary<int, ILinie> ReadFile(String filePath)
        {
            FileHelperEngine<LinieRecord> engine = new FileHelperEngine<LinieRecord>();
            ConcurrentDictionary<int, ILinie> linien = new ConcurrentDictionary<int, ILinie>();

            try {
                engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;
                engine.Encoding = Encoding.UTF8;
                LinieRecord[] res = engine.ReadFile(filePath);

                foreach (LinieRecord linie in res) {
                    //Übernehmen der eingelesenen Daten in das Programm-Model:
                    ILinie transport = new Linie();
                    transport.Bezeichnung = linie.Bezeichnung;
                    transport.Echtzeit = linie.Echtzeit;
                    transport.Id = linie.Id;
                    transport.Reihenfolge = linie.Reihenfolge;
                    transport.Verkehrsmittel = Linie.VerkehrsmittelConverter(linie.Verkehrsmittel);

                    //Schreiben des Models in Collection für den Rückgabewert:
                    linien.AddOrUpdate(transport.Id, transport, (key, oldValue) => transport);
                }
            } catch (Exception ex) {
                //Dokument konnte nicht geparst werden (Nicht vorhanden/geöffnet)
                throw new VtmParsingException("Beim Versuch die Linien zu parsen ist ein Fehler aufgetreten!", filePath, ex);
            }

            return (linien);
        }
开发者ID:CodefoundryDE,项目名称:ViennaTrafficMonitor,代码行数:29,代码来源:LinienParser.cs

示例10: CanHandleMultipleWorkItemInstances

        public async Task CanHandleMultipleWorkItemInstances()
        {
            var metrics = new InMemoryMetricsClient();
            var queue = new InMemoryQueue<WorkItemData>(retryDelay: TimeSpan.Zero, retries: 0);
            queue.AttachBehavior(new MetricsQueueBehavior<WorkItemData>(metrics));
            var messageBus = new InMemoryMessageBus();
            var handlerRegistry = new WorkItemHandlers();
            var j1 = new WorkItemJob(queue, messageBus, handlerRegistry);
            var j2 = new WorkItemJob(queue, messageBus, handlerRegistry);
            var j3 = new WorkItemJob(queue, messageBus, handlerRegistry);
            int errors = 0;
            var jobIds = new ConcurrentDictionary<string, int>();

            handlerRegistry.Register<MyWorkItem>(ctx => {
                var jobData = ctx.GetData<MyWorkItem>();
                Assert.Equal("Test", jobData.SomeData);

                jobIds.AddOrUpdate(ctx.JobId, 1, (key, value) => value + 1);
                
                for (int i = 0; i < 10; i++)
                    ctx.ReportProgress(10 * i);

                if (RandomData.GetBool(1))
                {
                    Interlocked.Increment(ref errors);
                    throw new ApplicationException("Boom!");
                }
                
                return TaskHelper.Completed();
            });

            for (int i = 0; i < 100; i++)
                queue.Enqueue(new MyWorkItem { SomeData = "Test", Index = i }, true);
            
            var completedItems = new List<string>();
            object completedItemsLock = new object();
            messageBus.Subscribe<WorkItemStatus>(status =>
            {
                if (status.Progress < 100)
                    return;

                lock (completedItemsLock)
                    completedItems.Add(status.WorkItemId);
            });
            
            var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            var token = cancellationTokenSource.Token;
            var tasks = new List<Task>();
            tasks.AddRange(new[] {
                Task.Run(async () => await j1.RunUntilEmptyAsync(token), token),
                Task.Run(async () => await j2.RunUntilEmptyAsync(token), token),
                Task.Run(async () => await j3.RunUntilEmptyAsync(token), token),
            });

            await Task.WhenAll(tasks);
            Thread.Sleep(10);
            Assert.Equal(100, completedItems.Count + errors);
            Assert.Equal(3, jobIds.Count);
            Assert.Equal(100, jobIds.Sum(kvp => kvp.Value));
        }
开发者ID:vebin,项目名称:Foundatio,代码行数:60,代码来源:WorkItemJobTests.cs

示例11: TestRandomness

        public void TestRandomness(Func<List<int>> getRandomList, int rangeLength, int count)
        {
            var combinations = rangeLength.Factorial(rangeLength - count + 1);
            var iterations = combinations * 100;
            var ocurrences = new ConcurrentDictionary<long, int>(Environment.ProcessorCount, (int)combinations);

            var partitioner = Partitioner.Create(0, (long)iterations);
            Parallel.ForEach(partitioner, new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount},
                range =>
                {
                    //hopefully having a private dictionary will help concurrency
                    var privateOcurrences = new Dictionary<long, int>();
                    for (long i = range.Item1; i < range.Item2; ++i)
                    {
                        var list = getRandomList();
                        //this will only work when numbers are between 0 and 88
                        long acc = list.Aggregate<int, long>(0, (current, value) => (value + 11) + current*100);
                        privateOcurrences.AddOrUpdate(acc, 1, v => v + 1);
                    }
                    foreach (var privateOcurrence in privateOcurrences)
                    {
                        ocurrences.AddOrUpdate(privateOcurrence.Key,
                            privateOcurrence.Value,
                            (k, v) => v + privateOcurrence.Value);
                    }
                });

            var averageOcurrences = iterations / (combinations * 1.0m);
            var currentAverage = ocurrences.Values.Average();
            Debug.WriteLine("The average ocurrences of this implementation is {0} comparing to {1} in the 'perfect' scenario", currentAverage, averageOcurrences);
            Assert.Less(currentAverage, averageOcurrences * 1.05m);
            Assert.Greater(currentAverage, averageOcurrences * 0.95m);
        }
开发者ID:brunoss,项目名称:Toolbox,代码行数:33,代码来源:TestNonRepeatingGenerator.cs

示例12: DataReceived

        //buffer
        private void DataReceived(IList<DataRecord> dataRecords)
        {
            ConcurrentDictionary<EntityKey, Entity> buffer = new ConcurrentDictionary<EntityKey, Entity>();
            for (int i = 0; i < dataRecords.Count; i++)
            {
                var key = String.Intern(dataRecords[i].DataRecordKey);
                var name = String.Intern(dataRecords[i].PropertyName);
                var value = dataRecords[i].PropertyValue;
                Entity entity;
                bool isNew = !_entityIndex.TryGetValue(EntityBuilder.Fnv1Hash(key), out entity);

                // add
                if (isNew)
                {
                    entity = EntityBuilder.Build<Entity>(key, KeyType.Isin);
                    _entityIndex.TryAdd(entity.Key.HashedValue, entity);
                }

                // update
                entity.Values.AddOrUpdate(name, new EntityItem(value), (n, oldValue) => new EntityItem(value, oldValue.Value));
                buffer.AddOrUpdate(entity.Key, entity, (n, oldValue) => entity);
            }

            _eventExploder(buffer.Values);
        }
开发者ID:nagyist,项目名称:wpfrealtime,代码行数:26,代码来源:BaseServiceObserver.cs

示例13: Stack_WithLowThreadCount_WorksCorrectly

        public void Stack_WithLowThreadCount_WorksCorrectly(int threads, int pushes, int pops)
        {
            //The elements we insert are unique and sentinel value is -1
            int initialValue = -1;
            int currentValue = initialValue;
            ConcurrentDictionary<int, int> table = new ConcurrentDictionary<int, int>();
            Core.Stack.Stack<int> stack = new Core.Stack.Stack<int>(initialValue);

            ThreadBuilder
                .Empty()
                .AddThreads(() =>
                {
                    for (int i = 0; i < pushes; i++)
                    {
                        int value = Interlocked.Increment(ref currentValue);
                        stack.Push(value);
                    }
                }, threads)
                .AddThreads(() =>
                {
                    for (int i = 0; i < pops; i++)
                    {
                        int value = stack.Pop();
                        table.AddOrUpdate(value, x => 1, (k, v) => v + 1);
                    }
                }, threads)
                .Start();

            //The sentinel value can be returned more than once if stack is empty at the time of a pop
            int expectedPops = table.Keys.Count + (table.ContainsKey(initialValue) ? -1 : 0);
            int actualPops = table.Count(x => x.Key != initialValue && x.Value == 1);

            Assert.AreEqual(expectedPops, actualPops);
        }
开发者ID:ionuttamas,项目名称:LockFree,代码行数:34,代码来源:StackTests.cs

示例14: CacheTemplateHelper

 private void CacheTemplateHelper(ICompiledTemplate template, ITemplateKey templateKey, Type modelTypeKey)
 {
     var uniqueKey = templateKey.GetUniqueKeyString();
     _cache.AddOrUpdate(uniqueKey, key =>
     {
         // new item added
         _assemblies.Add(template.TemplateAssembly);
         var dict = new ConcurrentDictionary<Type, ICompiledTemplate>();
         dict.AddOrUpdate(modelTypeKey, template, (t, old) => {
             throw new Exception("Expected the dictionary to be empty."); });
         return dict;
     }, (key, dict) =>
     {
         dict.AddOrUpdate(modelTypeKey, t =>
         {
             // new item added (template was not compiled with the given type).
             _assemblies.Add(template.TemplateAssembly);
             return template;
         }, (t, old) =>
         {
             // item was already added before
             return template;
         });
         return dict;
     });
 }
开发者ID:MatthewSJones,项目名称:RazorEngine,代码行数:26,代码来源:InvalidatingCachingProvider.cs

示例15: Search

        public IEnumerable<SearchResult> Search(string text)
        {
            // find the unique tokens in the input
            var tokens = Tokenizer.Tokenize(text).Distinct().ToArray();

            if (0 == tokens.Length) return new SearchResult[] { };

            var results = new ConcurrentDictionary<string, IndexEntry<Metadata>[]>();

            Parallel.ForEach(tokens, x => results.TryAdd(x, this.indexStore.Query(x).ToArray()));

            var documents = new ConcurrentDictionary<string, List<string>>();

            // count the results
            Parallel.ForEach(results.Keys, token =>
                {
                    foreach (var doc in results[token])
                    {
                        documents.AddOrUpdate(doc.Value, new List<string>(new[] {token}), (t, x) =>
                            {
                                x.Add(token);
                                return x;
                            });
                    }
                });

            // resturn the results
            return documents.OrderByDescending(x => x.Value.Count()).Select(x => new SearchResult(x.Key, x.Value.ToArray()));
        }
开发者ID:richorama,项目名称:AzureStorageExtensions,代码行数:29,代码来源:TextSearchIndex.cs


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