Skip to content

aarace/TemporalBag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TemporalBag

A thread-safe, unordered collection for .NET where every item has a time-to-live (TTL). Items are invisible once they expire and are periodically removed by a background timer. No timers to manage, no manual eviction logic - just add items and let them age out.

Quick start

using TemporalBag.Core;

// Items expire after 30 seconds; background cleanup runs every 10 seconds (default).
using var bag = new TemporalBag<string>(maxAge: TimeSpan.FromSeconds(30));

bag.Add("hello");

foreach (var item in bag)
    Console.WriteLine(item); // only non-expired items are yielded

API

Construction

// Default cleanup interval (10 seconds)
var bag = new TemporalBag<string>(maxAge: TimeSpan.FromMinutes(5));

// Custom cleanup interval
var bag = new TemporalBag<string>(
    maxAge:          TimeSpan.FromMinutes(5),
    cleanupInterval: TimeSpan.FromMinutes(1));

The background cleanup timer compacts the internal list by physically removing expired entries. Items are always filtered at read time regardless of whether cleanup has run, so the cleanup interval only affects memory usage, not correctness.

Adding items

// Use the default TTL set at construction time
bag.Add("default-ttl-item");

// Override the TTL for a specific item
bag.Add("short-lived", TimeSpan.FromSeconds(5));
bag.Add("long-lived",  TimeSpan.FromHours(1));

Reference types and value types are both supported.

var intBag  = new TemporalBag<int>(TimeSpan.FromSeconds(10));
var guidBag = new TemporalBag<Guid>(TimeSpan.FromSeconds(10));

intBag.Add(42);
guidBag.Add(Guid.NewGuid());

Reading items

// Enumerate - only non-expired items are yielded
foreach (var item in bag)
    Console.WriteLine(item);

// LINQ works naturally
var matches = bag.Where(x => x.StartsWith("prefix")).ToList();

// Membership check
bool exists = bag.Contains("hello");

// Count only live items
int live = bag.Count;

Inspecting remaining lifetime

AsLive() returns each item paired with how much time it has left:

foreach (var (value, remaining) in bag.AsLive())
    Console.WriteLine($"{value} expires in {remaining.TotalSeconds:F1}s");

Manual cleanup and clearing

// Force a cleanup now - returns true if it ran, false if one was already in progress
bool ran = bag.CleanUp();

// Discard all items immediately, regardless of TTL
bag.Clear();

Disposal

TemporalBag<T> implements IDisposable. Always dispose it (or use a using statement) to stop the background timer.

using var bag = new TemporalBag<string>(TimeSpan.FromMinutes(1));
// timer is stopped automatically when the using block exits

How it works

Expiry is evaluated lazily - every enumeration, Count, and Contains call checks the current time and skips expired items. No item is ever returned to the caller after its TTL has elapsed.

The background cleanup timer compacts the internal ConcurrentBag by atomically swapping it for a fresh one and re-inserting only the items that are still live. This keeps memory bounded without affecting read correctness. Items added concurrently during a cleanup are never lost - the atomic swap ensures they land in the new bag directly.

Targets

  • netstandard2.0
  • net8.0
  • net10.0

License

MIT

About

A C# IEnumerable<T> collection that holds items that auto-expire, so any given enumerable only sees a rolling window of time.

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages