diff --git a/src/Components/Components/src/PersistentComponentState.cs b/src/Components/Components/src/PersistentComponentState.cs index d3f5e9fd9309..2d761fdc60c9 100644 --- a/src/Components/Components/src/PersistentComponentState.cs +++ b/src/Components/Components/src/PersistentComponentState.cs @@ -84,12 +84,10 @@ public PersistingComponentStateSubscription RegisterOnPersisting(Func call throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback."); } - if (_currentState.ContainsKey(key)) + if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options))) { throw new ArgumentException($"There is already a persisted object under the same key '{key}'"); } - - _currentState.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options)); } [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")] @@ -102,12 +100,10 @@ internal void PersistAsJson(string key, object instance, [DynamicallyAccessedMem throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback."); } - if (_currentState.ContainsKey(key)) + if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options))) { throw new ArgumentException($"There is already a persisted object under the same key '{key}'"); } - - _currentState.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options)); } /// @@ -124,12 +120,10 @@ internal void PersistAsBytes(string key, byte[] data) throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback."); } - if (_currentState.ContainsKey(key)) + if (!_currentState.TryAdd(key, data)) { throw new ArgumentException($"There is already a persisted object under the same key '{key}'"); } - - _currentState.Add(key, data); } ///