Adds a key/value pair to NamedMapTKey, TValue if the key does not already exist,
or updates a key/value pair in the NamedMapTKey, TValue if the key already exists.
Namespace: Soss.Client.Concurrent
Assembly: soss_namedcache (in soss_namedcache.dll) Version: 6.2.0.0
Syntax
public TValue AddOrUpdate( TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory )
Parameters
- key
- Type: TKey
The key to be added or whose value should be updated. - addValueFactory
- Type: SystemFuncTKey, TValue
The function used to generate a value for an absent key. - updateValueFactory
- Type: SystemFuncTKey, TValue, TValue
The function used to generate a new value for an existing key based on the key's existing value
Return Value
Type: TValueA new value for the key. This will be either the result of addValueFactory (if the key was absent) or the result of updateValueFactory (if the key was present).
Exceptions
Exception | Condition |
---|---|
ArgumentNullException | Thrown if key is a null reference or addValueFactory is a null reference or updateValueFactory is a null reference. |
TimeoutException | Thrown when the maximum number of internal retries reached. |
Examples
The following example illustrates how to use the AddOrUpdate method
using System; using System.Diagnostics; using Soss.Client; using Soss.Client.Concurrent; class AddOrUpdateUsage { static void Main(string[] args) { NamedMap<int, string> map = new NamedMap<int, string>("myMap"); // Both calls below should add new elements to the // map since these keys are not yet present there for (int key = 6; key <= 7; key++) { map.AddOrUpdate(key, (k) => { switch (k) { case 6: return "F"; case 7: return "G"; default: return "Unexpected"; } }, (k, oldValue) => "this 'update' arg will not be used" ); } // Verify one of the elements that was inserted above string value = map.GetOrAdd(7, "this 'add' arg will not be used"); Debug.Assert("G" == value); // Repeat the AddOrUpdate calls, resulting in an update to each element for (int key = 6; key <= 7; key++) { map.AddOrUpdate(key, "this 'add' arg will not be used", (k, oldValue) => { switch (oldValue) { case "F": return "FF"; case "G": return "GG"; default: return "Unexpected"; } } ); } // Verify one of the elements that was inserted above value = map.GetOrAdd(7, "this 'add' arg will not be used"); Debug.Assert("GG" == value); // Clean up map.Clear(); } }
See Also