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); }
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(); }
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; }
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(); }
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(); }); }
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); }
private void CountAndDecrement(EventWaitHandle eventWait) { eventWait.Set(); eventWait.Reset(); foreach (var pair in _eventsHandled) { if (pair.Value <= 0 && _users.TryGetValue(pair.Key, out User user)) { user.Online = false; } else { _eventsHandled.TryUpdate(pair.Key, pair.Value - 1, pair.Value); } } }
public bool ChangeStatus(string employeeID, EmployeeStatusType status) { if (!_emplDict.ContainsKey(employeeID)) { return(false); } if (!_emplDict.TryGetValue(employeeID, out var changeEmployeeModel)) { return(false); } if (changeEmployeeModel.Status == status) { return(true); } EmployeeModel newEmployeeModel = new EmployeeModel { ID = changeEmployeeModel.ID, Status = status }; if (!_emplDict.TryUpdate(employeeID, newEmployeeModel, changeEmployeeModel)) { return(false); } if (changeEmployeeModel.Status == EmployeeStatusType.Work && status == EmployeeStatusType.Free) { Interlocked.Increment(ref _countFreeEmployees); } if (changeEmployeeModel.Status == EmployeeStatusType.Free && status == EmployeeStatusType.Work) { Interlocked.Decrement(ref _countFreeEmployees); } using (EmployeeContext employeeContext = new EmployeeContext()) { var emplDTO = Mapper.Map <EmployeeDTO>(newEmployeeModel); employeeContext.Employees.AddOrUpdate(emplDTO); employeeContext.SaveChangesAsync(); } return(true); }
public void UpdateValue(string key, TValue value) { if (_dict.ContainsKey(key)) { TValue oldValue; _dict.TryGetValue(key, out oldValue); _dict.TryUpdate(key, value, oldValue); } string path = Path.Combine(_path, key + "." + _backingending); if (File.Exists(path)) { File.Delete(path); } CreateFile(new DiskData(key, value)); }
protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { string key = GetKey(request); if (blackList.Contains(key)) { return(request.CreateResponse(HttpStatusCode.Forbidden)); } var response = await base.SendAsync(request, cancellationToken); if (!Thread.CurrentPrincipal.Identity.IsAuthenticated && response.StatusCode == HttpStatusCode.Unauthorized && !String.IsNullOrEmpty(key)) { if (!ipStore.TryAdd(key, new List <DateTime>() { DateTime.Now })) { int durationSeconds = 30; List <DateTime> oldLog = null; ipStore.TryGetValue(key, out oldLog); var last30SecondsLog = new List <DateTime>( oldLog.Where(t => (DateTime.Now - t).TotalSeconds <= durationSeconds)); last30SecondsLog.Add(DateTime.Now); ipStore.TryUpdate(key, last30SecondsLog, oldLog); // 15 or more failed requests in the last 30 seconds if (last30SecondsLog.Count > 15) { lock (listLock) { blackList.Add(key); } } } } return(response); }
private async Task <IExecutionResult> AppendToStreamInternalAsync(string streamId, long expectedVersion, params InMemoryEventData[] events) { long eventPosition = 1; if (expectedVersion == ExpectedVersion.NoStream || expectedVersion == ExpectedVersion.Any) { await CreateNewStream(streamId, streamId, events); eventPosition++; } else { var existingStream = await this.ReadStreamEventsForwardAsync(streamId, 0, int.MaxValue); existingStream.ThrowsIf(stream => !existingStream.HasValue, new AggregateNotFoundException(streamId)) .ThrowsIf(stream => expectedVersion != stream.Value.Version, new WrongExpectedStreamVersionException(expectedVersion.ToString(), existingStream.Value.Version.ToString())); expectedVersion = expectedVersion + events.Length; var newVersionedStream = existingStream.Value.ChangeVersion(expectedVersion); eventPosition = newVersionedStream.NextEventNumber; } foreach (var @event in events) { var newEvent = InMemoryEvent.Create(@event.EventId, streamId, eventPosition, @event.EventType, @event, @event.EventMetadata, DateTime.Now); InMemoryStream existingStream; _inMemoryStore.TryGetValue(streamId, out existingStream); var updatedStream = existingStream.AppendEvents(new List <InMemoryEvent> { newEvent }); _inMemoryStore.TryUpdate(streamId, updatedStream, existingStream); eventPosition++; } return(ExecutionResult.Success); }
// Чтение файлов private static void ReadFiles(object x) { string path = (string)x; string[] files = Directory.GetFiles(path, "*.txt"); foreach (string fileName in files) { // Считываем из файла try { using (var sr = new StreamReader(fileName)) { while (sr.Peek() >= 0) { var s = sr.ReadLine(); // Проверяем на пустую строку if (string.IsNullOrWhiteSpace(s)) { continue; } // Проверяем минимальную длину строки if (!regex.IsMatch(s)) { continue; } try { dict.TryUpdate(s, ++dict[s], dict[s]); } catch (System.Collections.Generic.KeyNotFoundException exception) { dict.TryAdd(s, 1); } catch (Exception exception) { MessageBox.Show(exception.Message); } } } } catch (Exception exception) { MessageBox.Show(exception.Message); } } }
private void ClearLocked <TKey, TValue>(ConcurrentDictionary <TKey, LinkedNode <TValue> > dict) where TValue : class { // this is safe only because we're write-locked foreach (var kvp in dict.Where(x => x.Value != null)) { if (kvp.Value.Gen < _liveGen) { var link = new LinkedNode <TValue>(null, _liveGen, kvp.Value); dict.TryUpdate(kvp.Key, link, kvp.Value); } else { kvp.Value.Value = null; } } }
/// <inheritdoc /> public void StoreBot(string key, bool shouldRestart) { if (Bots.ContainsKey(key)) { var oldValue = GetShouldRestartBot(key); if (!Bots.TryUpdate(key, shouldRestart, oldValue)) { _logger.Log($"Failed to update ShouldRestart value with the key: {key} from the dictionary", ConsoleColor.Red); } return; } if (!Bots.TryAdd(key, shouldRestart)) { _logger.Log($"Failed to add ShouldRestart value with the key: {key} from the dictionary", ConsoleColor.Red); } }
public async Task <bool> ExecuteInitScriptAsync(PackageIdentity identity) { var result = false; // Reserve the key. We can remove if the package has not been restored. if (TryMarkVisited(identity, PackageInitPS1State.NotFound)) { var nugetPaths = NuGetPathContext.Create(Settings.Value); var fallbackResolver = new FallbackPackagePathResolver(nugetPaths); var installPath = fallbackResolver.GetPackageDirectory(identity.Id, identity.Version); if (!string.IsNullOrEmpty(installPath)) { var scriptPath = Path.Combine(installPath, "tools", PowerShellScripts.Init); if (File.Exists(scriptPath)) { // Init.ps1 is present and will be executed. _initScriptExecutions.TryUpdate( identity, PackageInitPS1State.FoundAndExecuted, PackageInitPS1State.NotFound); var request = new ScriptExecutionRequest(scriptPath, installPath, identity, project: null); await ExecuteScriptCoreAsync(request); result = true; } } else { // Package is not restored. Do not cache the results. PackageInitPS1State dummy; _initScriptExecutions.TryRemove(identity, out dummy); result = false; } } else { // Key is already present. Simply access its value result = (_initScriptExecutions[identity] == PackageInitPS1State.FoundAndExecuted); } return(result); }
/// <summary> /// Registers an <see cref="IAmbientSettingInfo"/> in the global registry. /// </summary> /// <param name="setting">The <see cref="IAmbientSettingInfo"/> to register.</param> public void Register(IAmbientSettingInfo setting) { if (setting == null) { throw new ArgumentNullException(nameof(setting)); } WeakReference <IAmbientSettingInfo> newReference = new WeakReference <IAmbientSettingInfo>(setting); WeakReference <IAmbientSettingInfo> existingReference; int loopCount = 0; do { IAmbientSettingInfo?existingSetting; existingReference = _settings.GetOrAdd(setting.Key, newReference); // did we NOT succeed? if (newReference != existingReference) { // is the old one gone? if (!existingReference.TryGetTarget(out existingSetting)) { // overwrite that one--were we NOT able to overwrite it? if (!_settings.TryUpdate(setting.Key, newReference, existingReference)) { // Coverage note: the inside of this loop is nearly impossible to cover in tests // wait a bit and try again System.Threading.Thread.Sleep((int)Math.Pow(2, loopCount + 1)); continue; } // else we successfully overwrote it and there is no need to look for a conflict existingSetting = setting; } // the old one is still there, so we need to check for a conflict string existingDescription = existingSetting.Description ?? "<null>"; string description = setting.Description ?? "<null>"; string existingDefaultValueString = existingSetting.DefaultValueString; string defaultValueString = setting.DefaultValueString; if (!String.Equals(existingDescription, description, StringComparison.Ordinal) || !String.Equals(existingDefaultValueString, defaultValueString, StringComparison.Ordinal)) { throw new ArgumentException($"A setting with the key {setting.Key} has already been registered ({existingDescription} vs {description} or {existingDefaultValueString} vs {defaultValueString})!"); } // else we didn't succeed, but it doesn't look like there is a conflict anyway, so we're probably fine } // else we succeeded // raise the registered event SettingRegistered?.Invoke(null, setting); return; // Coverage note: the loop and exception is nearly impossible to cover in tests } while (loopCount++ < 10); throw new TimeoutException("Timeout attempting to register setting!"); }
private void StartTicks() { do { if (!_tickDictionary.IsEmpty) { var tick = _tickDictionary.OrderBy(x => Guid.NewGuid()).First().Value; tick = GetNextTick(tick); InternalTick(this, new InternalTickEventArgs { Tick = tick }); _tickDictionary.TryUpdate(tick.Symbol, tick, tick); } Thread.Sleep(NextInt(DotNetEnv.Env.GetInt("min", 10), DotNetEnv.Env.GetInt("max", 100))); } while (!_fakeQueue.CancellationToken.IsCancellationRequested); }
public async Task Notify(Check checkResults) { if (checkResults.Settings.EnvironmentId != (int)EnvironmentsEnum.Prod) { return; } CheckStatusAtTime prevNotification; var recordExists = _notificationsHistory.TryGetValue(checkResults.Settings.Type, out prevNotification); var currentStatus = checkResults.State.Status; if (currentStatus == StatusesEnum.CRITICAL) { if (!recordExists) { _notificationsHistory.TryAdd(checkResults.Settings.Type, new CheckStatusAtTime(currentStatus, true)); return; } if (prevNotification.IsFirstAdd && (DateTime.Now - prevNotification.NotificationTime) > TimeSpan.FromMinutes(NOTIFICATION_DELAY_MIN) || (DateTime.Now - prevNotification.NotificationTime) > TimeSpan.FromMinutes(NOTIFICATION_INTERVAL_MIN)) { await _telegramNotificationService.Notify(checkResults); var checkStatus = new CheckStatusAtTime(currentStatus, false); _notificationsHistory.TryUpdate(checkResults.Settings.Type, checkStatus, prevNotification); } } else { if (!recordExists) { //ok, warning. return; } //suspend sending to avoid spamming 'critical'-'recovery' within 2 minutes notifications if (!prevNotification.IsFirstAdd) { //recovery await _telegramNotificationService.Notify(checkResults); } _notificationsHistory.TryRemove(checkResults.Settings.Type, out var removed); } }
// Adds a single value to the history public void AddValue(T value) { if (m_insertPrep != null) { if (!m_insertPrep.PrepareForInsert(ref value)) { return; } } // Filter out common values if (m_commonDict != null) { bool tmp; if (m_commonDict.TryGetValue(value, out tmp)) { return; } } // Add or update the value. int attempts = 0; while (attempts < 3) { attempts++; double currentValue = 0; if (m_dict.TryGetValue(value, out currentValue)) { if (m_dict.TryUpdate(value, currentValue + 1, currentValue)) { break; } } else { if (m_dict.TryAdd(value, 1)) { break; } } } }
static void Main(string[] args) { //实现的是一个键 - 值集合类.它提供的方法有: //TryAdd:尝试向集合添加一个键 - 值 //TryGetValue:尝试返回指定键的值. //TryRemove:尝试移除指定键处的元素. //TryUpdate:尝试更新指定键的值. BankAccount account = new BankAccount(); ConcurrentDictionary <object, int> sharedDict = new ConcurrentDictionary <object, int>(); Task <int>[] tasks = new Task <int> [10]; for (int i = 0; i < tasks.Length; i++) { sharedDict.TryAdd(i, account.Balance); tasks[i] = new Task <int>((keyObj) => { int currentValue; bool gotValue; for (int j = 0; j < 1000; j++) { gotValue = sharedDict.TryGetValue(keyObj, out currentValue); sharedDict.TryUpdate(keyObj, currentValue + 1, currentValue); } int result; gotValue = sharedDict.TryGetValue(keyObj, out result); if (gotValue) { return(result); } else { throw new Exception(String.Format("No data item available for key {0}", keyObj)); } }, i); tasks[i].Start(); } for (int i = 0; i < tasks.Length; i++) { account.Balance += tasks[i].Result; } Console.WriteLine("Expected value {0}, Balance: {1}", 10000, account.Balance); Console.WriteLine("Press enter to finish"); Console.WriteLine(account.Balance); Console.ReadLine(); }
public async Task GetUserMessagesAsync(long screenId) { var response = await client.GetAsync($"ScreenBooking/GetScreenBookingsByScreenId?id={screenId}"); if (response.IsSuccessStatusCode) { var allScreenBookings = await response.Content.ReadAsAsync <List <ScreenBooking> >(); var currentDatetime = DateTime.UtcNow; var currentDate = currentDatetime.Date; var currentTime = (int)currentDatetime.TimeOfDay.TotalSeconds; int targetTime = currentTime + 2 * 60; var screenBookings = allScreenBookings.Where(s => !s.Displayed && s.ScheduledDate == currentDate && s.ScheduledStartTime >= currentTime && s.ScheduledStartTime < targetTime).OrderBy(s => s.ScheduledStartTime).ToArray(); foreach (var item in screenBookings) { var requestId = item.RequestId; Request request = await this.GetRequestInfo(requestId); if (request != null) { int startTime = item.ScheduledStartTime; var message = new Message { ScreenBooking = item, Type = (MessageType)Enum.Parse(typeof(MessageType), request.MessageTypeId.ToString()), Content = request.Text, // Sender = request.UserId.ToString(), StartTime = startTime, Duration = item.ScheduledDuration }; if (!UserMessages.ContainsKey(startTime)) { UserMessages.TryAdd(startTime, message); } else { UserMessages.TryUpdate(startTime, message, UserMessages[startTime]); } } } } return; }
public bool TryUpdateUser(GameClient Session) { if (Session == null) { return(false); } UserCache OldData; TryGetUser(Session.GetHabbo().Id, out OldData); using (UserCache NewData = new UserCache(Session.GetHabbo().Id, Session.GetHabbo().Username, Session.GetRoleplay().Class, Session.GetHabbo().Look, Session.GetRoleplay().MarriedTo, Session.GetRoleplay().Level, GetUserComponent.ReturnUserStatistics(Session))) { _usersCached.TryUpdate(Session.GetHabbo().Id, NewData, OldData); } return(true); }
public Task AddOrUpdateGranularPermission(GranularPermission granularPermission) { var formattedId = FormatId(granularPermission.Id); var success = _granularPermissions.TryAdd(formattedId, granularPermission); if (!success) { granularPermission.Track(false); _granularPermissions.TryUpdate(formattedId, granularPermission, _granularPermissions[formattedId]); } else { granularPermission.Track(); } return(Task.CompletedTask); }
public void Update(string key, T value, int expireSec = 0) { if (!ContainsKey(key)) { Add(key, value); } else { var currentValue = new CacheWithExpire <T> { Value = value }; if (expireSec > 0) { currentValue.ExpireTime = DateTime.Now.AddSeconds(expireSec); } CacheModel.TryUpdate(key, currentValue, null); } }
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 unconditionally int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2); int r2 = dict.GetOrAdd("5k2", 4); Console.ReadKey(); }
void IServerSentEventsClient.RemoveEventListener(string @event, Action <ServerSentEventsMessage> handler) { if (string.IsNullOrWhiteSpace(@event)) { throw new ArgumentNullException(nameof(@event)); } if (handler == null) { throw new ArgumentNullException(nameof(handler)); } if (m_eventListeners.TryGetValue(@event, out var handlers)) { if (!m_eventListeners.TryUpdate(@event, handlers.Remove(handler), handlers)) { m_logger.LogWarning($"Can't remove event handler \"{@event}\""); } } }
/// <summary>管理下にある設定情報を更新、また存在していない場合は登録します</summary> /// <param name="type"></param> /// <param name="setting"></param> /// <returns></returns> internal bool UpdateOrAddSetting(Type type, object setting) { if (_settingDictionary.ContainsKey(type)) { if (_settingDictionary.TryUpdate(type, setting, _settingDictionary[type]) == false) { //todo:log return(false); } } else { //todo;log return(AddSetting(type, setting)); } return(true); }
/// <inheritdoc /> public void StorePrefix(string prefix, ulong key) { if (ServerPrefixes.ContainsKey(key)) { var oldPrefix = GetPrefix(key); if (!ServerPrefixes.TryUpdate(key, prefix, oldPrefix)) { this._logger.Log($"Failed to update custom prefix {prefix} with the key: {key} from the dictionary"); } return; } if (!ServerPrefixes.TryAdd(key, prefix)) { this._logger.Log($"Failed to add custom prefix {prefix} with the key: {key} from the dictionary"); } }
public static void Main() { var dict = new ConcurrentDictionary <string, int>(); if (dict.TryAdd("k1", 53)) { Console.WriteLine("Added"); } if (dict.TryUpdate("k1", 12, 53)) { Console.WriteLine("53 updated to 12"); } dict["k1"] = 53; // Overwrite unconditionally int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2); int r2 = dict.GetOrAdd("k2", 3); Console.Read(); }
public string TakeOwnership(string alias, Guid token, string candidateIdentifier) { if (token == Guid.Empty || string.IsNullOrWhiteSpace(candidateIdentifier)) { return(null); } var newValue = new AliasDetails { Owner = candidateIdentifier, Token = token }; if (_registeredAliases.TryGetValue(alias, out var registeredAlias)) { _registeredAliases.TryUpdate(alias, newValue, registeredAlias); return(registeredAlias.Owner); } _registeredAliases.TryAdd(alias, newValue); return(null); }
/// <inheritdoc cref="ICacheAdapter"/> public CachedTrip UpdateTripCache(StopEventResult stopEvent) { var cacheTrip = new CachedTrip(stopEvent); var uniqueTripKey = $"{cacheTrip.OperatingDayRef}_{cacheTrip.JourneyRef}"; if (!_tripCache.TryGetValue(uniqueTripKey, out var existCacheTrip)) { throw new CacheAlreadyExistsException($"Trip Cache - {uniqueTripKey} - Did not exist."); } ; if (!_tripCache.TryUpdate(uniqueTripKey, cacheTrip, existCacheTrip)) { throw new CacheAlreadyExistsException($"Trip Cache - {uniqueTripKey} - Update failed exist."); } ; return(cacheTrip); }
public void Update(IEnumerable <UpdateDataItem> items, OrderBookSides side) { foreach (var entry in items) { if (side == OrderBookSides.Buy) { var updatedEntry = new OrderBookEntry(entry.Id, entry.Size, _bids[entry.Id].Price); _bids.TryUpdate(entry.Id, updatedEntry, _bids[entry.Id]); } else if (side == OrderBookSides.Sell) { var updatedEntry = new OrderBookEntry(entry.Id, entry.Size, _asks[entry.Id].Price); _asks.TryUpdate(entry.Id, updatedEntry, _asks[entry.Id]); } } }
public override IJournalWriter CreateJournalWriter(long journalNumber, long journalSize) { var name = JournalName(journalNumber); var path = Path.Combine(_journalPath, name); var result = _journals.GetOrAdd(name, _ => new Lazy <IJournalWriter>(() => new Win32FileJournalWriter(path, journalSize))); if (result.Value.Disposed) { var newWriter = new Lazy <IJournalWriter>(() => new Win32FileJournalWriter(path, journalSize)); if (_journals.TryUpdate(name, newWriter, result) == false) { throw new InvalidOperationException("Could not update journal pager"); } result = newWriter; } return(result.Value); }
// An atomic operation means that it will be started and finished as a single step without other threads interfering public MainListing1X34() { 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); Console.ReadLine(); }
public override void Exec() { var dict = new ConcurrentDictionary <string, int>(); if (dict.TryAdd("key1", 42)) { Console.WriteLine("Added 42 to key1"); } if (dict.TryUpdate("key1", 21, 42)) { Console.WriteLine("42 updated to 21 for key1"); } dict["key1"] = 42; // Overwrite unconditionally int r1 = dict.AddOrUpdate("key1", 3, (theKey, theValue) => theValue * 2); int r2 = dict.GetOrAdd("key2", 3); Console.WriteLine("r1 contains {0} and r2 contains {1}", r1, r2); }
public bool CheckAddRequest(string userId) { var now = DateTime.Now; if (_lastRequests.TryGetValue(userId, out var time)) { if (time < now - new TimeSpan(0, 0, 2)) { _lastRequests.TryUpdate(userId, now, time); return(true); } return(false); } _lastRequests.TryAdd(userId, now); return(true); }
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(); }
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); }
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(); }
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; } } } }
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); }
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(); }
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(); }
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!"); }
private void CreateTestdictionary(Tree<string> outerTree, ConcurrentDictionary<string, IList<string>> dictionary) { IList<Tree<string>> nTree = outerTree.NTree; if (nTree != null) { var children = from n in nTree where !string.IsNullOrEmpty(n.Data) select n.Data; IList<string> list = null; if ((dictionary.TryGetValue(outerTree.Data, out list))) dictionary.TryUpdate(outerTree.Data, children.ToList<string>(), list); else dictionary.TryAdd(outerTree.Data, children.ToList<string>()); foreach (var tree in nTree) { CreateTestdictionary(tree, dictionary); } } else { IList<string> list = null; if (!(dictionary.TryGetValue(outerTree.Data, out list))) dictionary.TryAdd(outerTree.Data, new List<string>()); } }
static void MainFunction() { var con = new ConcurrentDictionary<string, int>(); con.TryAdd("cat", 1); con.TryAdd("dog", 2); //Try to update if value is 4 (fails) con.TryUpdate("cat", 200, 4); //Try to update if value is 2 (works) con.TryUpdate("dog", 100, 2); con.TryUpdate("cat", 500, 1); Console.WriteLine(con["cat"]); }
private static void DictionaryConcurrent() { // In standard Dictionray, we use Add or Remove or indexing to update (myDictionary["key"] // In ConcurrentDictionary, we use TryAdd(), TryRemove(), TryUpdate() etc // In standard Dictionray Add, Remove or indexing will throw exception // In ConcurrentDictionray, ryAdd(), TryRemove(), TryUpdate() will not throw exception // thus follows the rule of atomic method, which is : AtomicMethod(); [press F12 in this method to learn] var stock = new ConcurrentDictionary<string, int>(); stock.TryAdd("jDays", 4); stock.TryAdd("technolgyhour", 3); Console.WriteLine(string.Format("No. of shirts in stock = {0}", stock.Count)); bool success = stock.TryAdd("pluralsight", 6); Console.WriteLine("Added succeeded? " + success); success = stock.TryAdd("pluralsight", 6); Console.WriteLine("Added succeeded? " + success); stock["budidstgeeks"] = 5; //stock["pluralsight"] = 7; success = stock.TryUpdate("pluralsight", 7, 6); // update from 6 to 7 Console.WriteLine(string.Format("pluralsight = {0}, did update work? {1}", stock["pluralsight"], success)); success = stock.TryUpdate("pluralsight", 8, 6); // update from 6 to 8. but previously, we changed from 6 to 7. So, rather throwing an expcetion, this line will return false Console.WriteLine(string.Format("pluralsight = {0}, did update work? {1}", stock["pluralsight"], success)); int jDaysValue; success = stock.TryRemove("jDays", out jDaysValue); Console.WriteLine("value removed was: " + success); Console.WriteLine("\r\nEnumerating:"); foreach (var keyValPair in stock) { Console.WriteLine("{0}: {1}", keyValPair.Key, keyValPair.Value); } }
static void Main(string[] args) { /* BlockingCollection<string> col = new BlockingCollection<string>(); Task read = Task.Run(() => { //while (true) //{ // Console.WriteLine(col.Take()); //} foreach (string v in col.GetConsumingEnumerable()) Console.WriteLine(v); }); Task write = Task.Run(() => { while (true) { string s = Console.ReadLine(); if (string.IsNullOrWhiteSpace(s)) break; col.Add(s); } }); write.Wait(); */ /* ConcurrentBag<int> bag = new ConcurrentBag<int>(); bag.Add(42); bag.Add(21); int result; if(bag.TryTake(out result)) { Console.WriteLine(result); } if (bag.TryPeek(out result)) { Console.WriteLine("There is a next item: {0}", result); } */ /* ConcurrentBag<int> bag = new ConcurrentBag<int>(); Task.Run(() => { bag.Add(42); //Thread.Sleep(1000); bag.Add(21); bag.Add(35); Thread.Sleep(1000); bag.Add(88); }); Task.Run(() => { foreach (int i in bag) { Console.WriteLine(i); } }).Wait(); */ /* ConcurrentStack<int> stack = new ConcurrentStack<int>(); stack.Push(42); int result; if(stack.TryPop(out result)) { Console.WriteLine("Popped: {0}", result); } stack.PushRange(new int[] { 1, 2, 3 }); int[] values = new int[2]; //int[] values = new int[3]; stack.TryPopRange(values); foreach (int i in values) { Console.WriteLine(i); } */ /* ConcurrentQueue<int> queue = new ConcurrentQueue<int>(); queue.Enqueue(42); //queue.Enqueue(21); //queue.Enqueue(35); //queue.Enqueue(42); //queue.Enqueue(49); int result; if (queue.TryDequeue(out result)) { Console.WriteLine("Dequeue: {0}", result); } */ 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"); Console.WriteLine("First time is {0}",dict["k1"]); } dict["k1"] = 42; Console.WriteLine("Second time is {0}", dict["k1"]); int r1 = dict.AddOrUpdate("k1", 4, (s, i) => i * 4); int r2 = dict.GetOrAdd("k2", 3); Console.WriteLine("Third time is {0}", dict["k1"]); Console.WriteLine("First time dict[k2] is {0}", dict["k2"]); }
public static ConcurrentDictionary<string, int> count(LinkedList<string> input) { int c = 0; LinkedList<string> wordlist = getWordlist(); ConcurrentDictionary<String, int> wordcount = new ConcurrentDictionary<String, int>(); foreach(string currentline in input) { string replace = currentline; char[] remove = new char[] {'.',':','\'','#','!','=','-','+',';','<','>','{','}','(',')',' ','*','/','%',',','\\','\t','[',']'}; string[] line= replace.Split(remove,StringSplitOptions.RemoveEmptyEntries); //Split(remove,StringSplitOptions.RemoveEmptyEntries).Join(' '); //string[] line = currentline.Split(' '); Parallel.ForEach(wordlist, word => { int count = 0; foreach(string test in line) { if (test == word) { count++; } } int x = wordcount.GetOrAdd(word,0); count += x; while (!wordcount.TryUpdate(word,count,x)); }); c = c + line.Length; } while (!wordcount.TryAdd("WC", c)) ; return wordcount; }
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); }