Skip to content

Conversation

@bitfaster
Copy link
Owner

@bitfaster bitfaster commented Jul 17, 2022

Provide an explicit ScopedCache to ease working with scoped IDisposable values. All read operations are prefixed with 'Scoped' and return lifetimes instead of values. Scoped methods implement logic to ensure the lifetime returned is always valid.

public class Foo
{
    private const int capacity = 666;
    private ScopedCache<int, SomeDisposable> lru = new(new ConcurrentLru<int, Scoped<SomeDisposable>>(capacity));

    public void Bar()
    {
        var valueFactory = new SomeDisposableValueFactory();

        using (var lifetime = lru.ScopedGetOrAdd(1, k => valueFactory.Create(k)))
        {
            // lifetime.Value is guaranteed to be alive until the lifetime is disposed
        }
    }
}

public class SomeDisposableValueFactory
{
    public Scoped<SomeDisposable> Create(int key)
    {
        return new Scoped<SomeDisposable>(new SomeDisposable(key));
    }
}

@bitfaster bitfaster marked this pull request as ready for review July 17, 2022 19:47
@bitfaster bitfaster merged commit b2b7b92 into main Jul 17, 2022
@bitfaster bitfaster deleted the users/alexpeck/scopedec branch July 17, 2022 22:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants