diff --git a/FastCache/FastCache.cs b/FastCache/FastCache.cs index bfd1b09..88e7c64 100644 --- a/FastCache/FastCache.cs +++ b/FastCache/FastCache.cs @@ -184,7 +184,30 @@ public TValue GetOrAdd(TKey key, Func valueFactory, TimeSpan ttl) if (TryGet(key, out var value)) return value; - return _dict.GetOrAdd(key, (k, v) => new TtlValue(v.valueFactory(k), v.ttl), (ttl, valueFactory)).Value; + return _dict.GetOrAdd( + key, + (k, arg) => new TtlValue(arg.valueFactory(k), arg.ttl), + (ttl, valueFactory) + ).Value; + } + + /// + /// Adds a key/value pair by using the specified function if the key does not already exist, or returns the existing value if the key exists. + /// + /// The key to add + /// The factory function used to generate the item for the key + /// TTL of the item + /// Argument value to pass into valueFactory + public TValue GetOrAdd(TKey key, Func valueFactory, TimeSpan ttl, TArg factoryArgument) + { + if (TryGet(key, out var value)) + return value; + + return _dict.GetOrAdd( + key, + (k, arg) => new TtlValue(arg.valueFactory(k, arg.factoryArgument), arg.ttl), + (ttl, valueFactory, factoryArgument) + ).Value; } /// diff --git a/UnitTests/UnitTests.cs b/UnitTests/UnitTests.cs index 8a9accf..91be0b9 100644 --- a/UnitTests/UnitTests.cs +++ b/UnitTests/UnitTests.cs @@ -123,6 +123,18 @@ public async Task TestGetOrAdd() Assert.IsFalse(cache.TryGet("key", out _)); } + [TestMethod] + public async Task TestGetOrAddWithArg() + { + var cache = new FastCache(); + cache.GetOrAdd("key", (k, arg) => 1024 + arg.Length, TimeSpan.FromMilliseconds(100), "test123"); + Assert.IsTrue(cache.TryGet("key", out int res) && res == 1031); + + //eviction + await Task.Delay(110); + Assert.IsFalse(cache.TryGet("key", out _)); + } + [TestMethod] public void TestClear() {