Sunday, July 22, 2018

A thread-safe LazyList with low contention.

LazyList<T>

Nothing new in programming, but I've had a strong need for this special collection to be thread safe, allowing for multiple reads with a proper single write. For the most part this is done through a ReaderWriterLockSlim

Some advantages of this class:

  • Internally a "safe count" is defined to prevent any contention for records that do not require any locking (contention) and indexes below the safe count can be read while a write is occurring.
  • Proper progressive locking is also in place so that if the safe count is less than the record requested, it can still acquire a value and updates the safe count through Interlocked.CompareExchange. If more values in the list are required, an upgradable read is first required before potentially acquiring a write lock.
  • A thread safe enumerator is also provided through Interlocked.Increment. Enumerators can easily not be thread safe as multiple threads can enter the underlying state machine and cause trouble.
  • An 'endless' flag is provided to prevent infinite looping and will throw if values like .Count are called. This could be broken into to variants of this class, but this implementation makes for an more all-in-one approach and simpler LINQ extension implementation.
  • Properly Implements IDisposable and can be used with the using() keyword. This is mainly due to the underlying ReaderWriterLockSlim's disposability.

Source

https://github.com/electricessence/Open.Collections/blob/master/source/LazyList.cs

Original / Inspiration

http://www.fallingcanbedeadly.com/posts/crazy-extention-methods-tolazylist/

.Memoize() Extension

public static LazyList<T> Memoize<T>(this IEnumerable<T> list, bool isEndless = false) => new LazyList<T>(list, isEndless); 
A thread-safe LazyList<T> with low contention. Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team