TDArray.cs

Simple Concurrent Array Class

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
[Serializable]
public class TDArray<T> : IEnumerable<T>
{
    private          T[]               _array;
    private volatile MonitorActionFunc _maf;
    public volatile  int               Count;
    public TDArray(int cap)
    {
        _array = new T[cap];
        _maf   = new MonitorActionFunc();
        Count  = 0;
    }
    public int Length
    {
        get
        {
            var tmpThis = this;
            return tmpThis._maf.Lock(tmpThis, () => _array.Length);
        }
    }
    public T this[int index]
    {
        get
        {
            var array   = _array;
            var idx = index;
            var tmpThis = this;
            return tmpThis._maf.Lock(tmpThis, () =>
            {
                if (idx > array.Length)
                    throw new Exception("Error: Index out of range.");
                return array[idx];
            });
        }
        set
        {
            var tmpThis = this;
            var idx     = index;
            tmpThis._maf.Lock(tmpThis, () =>
            {
                if (idx >= _array.Length)
                    Array.Resize(ref _array, idx * 2);
                _array[idx] = value;
            });
        }
    }
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public void Add(T item)
    {
        var tmpThis = this;
        tmpThis._maf.Lock(tmpThis, () =>
        {
            if (Count >= _array.Length)
                Array.Resize(ref _array, _array.Length + _array.Length / 4 * 3);
            _array[Count] = item;
            Interlocked.Increment(ref Count);
        });
    }
    public void Clear()
    {
        var tmpThis = this;
        tmpThis._maf.Lock(tmpThis, () =>
        {
            Array.Clear(_array, 0, _array.Length);
            Count = 0;
        });
    }
    public IEnumerator<T> GetEnumerator()
    {
        var tmpThis = this;
        return tmpThis._maf.Lock(tmpThis, () =>
        {
            return GetEnum();
        });
    }
    private IEnumerator<T> GetEnum()
    {
        var array = _array;
        var count = Count;
        for (var i = 0; i < count; i++)
            yield return array[i];
    }
}

DynamicFSList.cs

Fast Search Concurrent Non-Concurrent List

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
public class DynamicFSList<T> : MonitorActionFunc, IEnumerable<T>
{
    private static IEqualityComparer<T> Comparer;
    private         VerticalList[]       _verticalLists;
    public          int                  Count;

    /// <summary>
    /// The initial size should be at least 1/8 of the expected total number of objects.
    /// For faster searching make initial size equal to the expected total number of objects.
    /// </summary>
    /// <param name="size"></param>
    public DynamicFSList(int size) : this(size, EqualityComparer<T>.Default)
    {
    }
    public DynamicFSList(int size, IEqualityComparer<T> comparer)
    {
        if (comparer == null)
            comparer = EqualityComparer<T>.Default;
        Comparer       = comparer;
        _verticalLists = new VerticalList[size];
        Count          = 0;
    }
    public (int mDepth, int index) MaximumListLength => GetMaximumListLength();
    public int                     TrueItemCount     => GetItemCount();
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public IEnumerator<T> GetEnumerator()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            return GetEnum();
        });
    }
    public void Clear()
    {
        _verticalLists.Clear();
    }
    public void Add(T item)
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            var hashCode = Comparer.GetHashCode(item) & int.MaxValue;
            var pos      = hashCode % _verticalLists.Length;
            if (_verticalLists[pos] == null)
                _verticalLists[pos] = new VerticalList();
            _verticalLists[pos].Add(item);
            Count++;
            if (Count > _verticalLists.Length << 3)
                EnsureSize();
        });
    }
    public int AddWithLocation(T item)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var hashCode = Comparer.GetHashCode(item) & int.MaxValue;
            var pos      = hashCode % _verticalLists.Length;
            if (_verticalLists[pos] == null)
                _verticalLists[pos] = new VerticalList();
            _verticalLists[pos].Add(item);
            Count++;
            if (Count > _verticalLists.Length << 3)
                EnsureSize();
            return FindEntry(item, hashCode);
        });
    }
    public T[] ToArray()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var newArray = new T[Count];
            var ptr      = 0;
            for (var i = 0; i < _verticalLists.Length; i++)
                if (_verticalLists[i] != null)
                    for (var j = 0; j < _verticalLists[i].Count; ++j)
                    {
                        newArray[ptr] = _verticalLists[i].Values[j];
                        ptr++;
                    }
            return newArray;
        });
    }
    private (int mDepth, int index) GetMaximumListLength()
    {
        var max = 0;
        var j   = 0;
        for (var i = 0; i < _verticalLists.Length; i++)
            if (_verticalLists[i] != null)
            {
                var count = _verticalLists[i].Count;
                if (count > max)
                {
                    max = count;
                    j   = i;
                }
            }
        return (max, j);
    }
    private int GetItemCount()
    {
        var count = 0;
        for (var i = 0; i < _verticalLists.Length; i++)
            if (_verticalLists[i] != null)
            {
                var c = _verticalLists[i].Count;
                count += c;
            }
        return count;
    }
    public int FindEntry(T item)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var hashCode = Comparer.GetHashCode(item) & int.MaxValue;
            return FindEntry(item, hashCode);
        });
    }
    private int FindEntry(T item, int hashCode)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            if (Count == 0)
                return -1;
            var pos = hashCode % _verticalLists.Length;
            if (_verticalLists[pos] == null)
                _verticalLists[pos] = new VerticalList();
            foreach (var i in _verticalLists[pos].Values)
                if (Comparer.Equals(i, item))
                    return pos;
            return -1;
        });
    }
    private void EnsureSize()
    {
        var cArray  = ToArray();
        var newSize = Count >> (1 + Count);
        _verticalLists = new VerticalList[newSize];
        foreach (var i in cArray)
        {
            var hashCode = Comparer.GetHashCode(i) & int.MaxValue;
            var pos      = hashCode % _verticalLists.Length;
            if (_verticalLists[pos] == null)
                _verticalLists[pos] = new VerticalList();
            _verticalLists[pos].Add(i);
        }
    }
    public bool Contains(T item)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var hashCode = Comparer.GetHashCode(item) & int.MaxValue;
            return FindEntry(item, hashCode) != -1;
        });
    }
    private IEnumerator<T> GetEnum()
    {
        for (var i = 0; i < _verticalLists.Length; i++)
            if (_verticalLists[i] != null)
                for (var j = 0; j < _verticalLists[i].Count; ++j)
                    yield return _verticalLists[i].Values[j];
    }
    private class VerticalList
    {
        public int Count;
        public T[] Values;
        public VerticalList()
        {
            Values = new T[3];
            Count  = 0;
        }
        public void Add(T item)
        {
            if (Contains(item))
                return;
            if (Count >= Values.Length)
                Array.Resize(ref Values, Values.Length + 3);
            Values[Count] = item;
            Count++;
        }
        private bool Contains(T item)
        {
            foreach (var i in Values)
                if (Comparer.Equals(i, item))
                    return true;
            return false;
        }
    }
}

DynamicStack.cs

A Concurrent or Non-Concurrent LIFO Collection of Objects

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class DynamicStack<T> : MonitorActionFunc, IEnumerable<T>
{
    private volatile T[] _array;
    private volatile int _count;
    public DynamicStack() : this(101)
    {
    }
    public DynamicStack(int capacity)
    {
        _array = new T[capacity];
        _count = 0;
    }
    public DynamicStack(ICollection col)
    {
        if (col != null)
        {
            _array = new T[col.Count];
            _count = 0;
            var en = col.GetEnumerator();
            while (en.MoveNext())
                Push((T) en.Current);
        }
    }
    public DynamicStack(IEnumerable<T> col)
    {
        if (col != null)
        {
            var enumerable = col as T[] ?? col.ToArray();
            _array = new T[enumerable.Length];
            foreach (var i in enumerable)
                Push(i);
        }
    }
    public int Count
    {
        get
        {
            var tmpThis = this;
            return tmpThis.Lock(tmpThis, () =>
            {
                return _count;
            });
        }
    }
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return new Enumerator(this);
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator(this);
    }
    public void Clear()
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            _array.Clear();
            _count = 0;
        });
    }
    public bool Contains(T item)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var size             = _count;
            var equalityComparer = EqualityComparer<T>.Default;
            while (size-- > 0)
                if (_array[size] != null && equalityComparer.Equals(_array[size], item))
                    return true;
            return false;
        });
    }
    public T Peek()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () => _array[_count - 1]);
    }
    public T Pop()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            _count--;
            var TVal = _array[_count];
            _array[Count] = default;
            return TVal;
        });
    }
    public void Push(T item)
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            if (_count + 1 > _array.Length)
                EnsureSize();
            _array[_count++] = item;
        });
    }
    private void EnsureSize()
    {
        var array = _array;
        Array.Resize(ref array, _array.Length << 1);
        _array = array;
    }
    public T[] ToArray()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var ta = new T[_count];
            for (var i = 0L; i < _count; ++i)
                ta[i] = _array[_count - i - 1];
            return ta;
        });
    }
    [Serializable]
    public class Enumerator : IEnumerator<T>
    {
        private readonly DynamicStack<T> _stack;
        private          int             _index;
        internal Enumerator(DynamicStack<T> stack)
        {
            _stack  = stack;
            _index  = int.MaxValue;
            Current = default;
        }
        public T Current
        {
            get;
            private set;
        }
        object IEnumerator.Current => Current;
        public void Dispose()
        {
            _index = int.MaxValue - 1;
        }
        public bool MoveNext()
        {
            var tmpThis = _stack;
            return tmpThis.Lock(tmpThis, () =>
            {
                if (_index == int.MaxValue)
                {
                    _index = _stack.Count - 1;
                    if (_index < int.MaxValue - 1)
                        Current = _stack._array[_index];
                    return _index < int.MaxValue - 1;
                }
                if (_index == int.MaxValue - 1)
                    return false;
                _index--;
                Current = !(_index < int.MaxValue - 1) ? default : _stack._array[_index];
                return _index < int.MaxValue - 1;
            });
        }
        void IEnumerator.Reset()
        {
            _index  = int.MaxValue;
            Current = default;
        }
    }
}

DynamicQueue.cs

A FIFO Collection of Objects, Concurrent, Non-Concurrent

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class DynamicQueue<T> : MonitorActionFunc, IEnumerable<T>
{
    private volatile T[] _array;
    private volatile int _head;
    private volatile int _scope;
    private volatile int _tail;
    public DynamicQueue() : this(1048576)
    {
    }
    public DynamicQueue(int capacity)
    {
        _array = new T[capacity];
        _scope = 0;
        _head  = 0;
        _tail  = 0;
    }
    public DynamicQueue(ICollection col)
    {
        if (col != null)
        {
            _array = new T[col.Count];
            _scope = 0;
            _head  = 0;
            _tail  = 0;
            var en = col.GetEnumerator();
            while (en.MoveNext())
                Enqueue((T) en.Current);
        }
    }
    public DynamicQueue(IEnumerable<T> col)
    {
        if (col != null)
        {
            _array = new T[col.Count()];
            _scope = 0;
            _head  = 0;
            _tail  = 0;
            using (var en = col.GetEnumerator())
            {
                while (en.MoveNext())
                    Enqueue(en.Current);
            }
        }
    }
    public int Count
    {
        get
        {
            var tmpThis = this;
            return tmpThis.Lock(tmpThis, () =>
            {
                return _scope;
            });
        }
    }
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return new Enumerator(this);
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator(this);
    }
    public void Clear()
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            _array.Clear();
            _scope = 0;
            _head  = 0;
            _tail  = 0;
        });
    }
    public bool Contains(T item)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var size             = _scope;
            var equalityComparer = EqualityComparer<T>.Default;
            while (size-- > 0)
                if (_array[size] != null && equalityComparer.Equals(_array[size], item))
                    return true;
            return false;
        });
    }
    public T Peek()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            if (_scope <= 0)
                throw new Exception("Queue is Empty.");
            return _array[_head];
        });
    }
    public T Dequeue()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            if (_scope <= 0)
                throw new Exception("Queue is Empty.");
            var TVal = _array[_head];
            _array[_head] = default;
            _head++;
            _scope--;
            return TVal;
        });
    }
    public void Enqueue(T item)
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            if (Count + 1 > _array.Length)
                EnsureSize();
            _array[_tail] = item;
            _tail++;
            _scope++;
        });
    }
    private void EnsureSize()
    {
        var array = _array;
        Array.Resize(ref array, _array.Length << 1);
        _array = array;
    }
    public T[] ToArray()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var ta  = new T[_scope];
            var ptr = 0L;
            for (var i = _head; i < _scope + _head; ++i)
                ta[ptr++] = _array[i];
            return ta;
        });
    }
    [Serializable]
    public class Enumerator : IEnumerator<T>
    {
        private readonly DynamicQueue<T> _q;
        private          T               _current;
        private          int             _index;
        internal Enumerator(DynamicQueue<T> q)
        {
            _q       = q;
            _index   = -1;
            _current = default;
        }
        public T Current
        {
            get
            {
                var tmpThis = _q;
                return tmpThis.Lock(tmpThis, () =>
                {
                    if (_index < 0)
                    {
                        if (_index == -1)
                            throw new Exception("Enumeration not started.");
                        throw new Exception("Enumeration ended.");
                    }
                    return _current;
                });
            }
        }
        object IEnumerator.Current
        {
            get
            {
                var tmpThis = _q;
                return tmpThis.Lock(tmpThis, () =>
                {
                    if (_index < 0)
                    {
                        if (_index == -1)
                            throw new Exception("Enumeration not started.");
                        throw new Exception("Enumeration ended.");
                    }
                    return _current;
                });
            }
        }
        public void Dispose()
        {
            _index = -2;
        }
        public bool MoveNext()
        {
            var tmpThis = _q;
            return tmpThis.Lock(tmpThis, () =>
            {
                if (_index == -2)
                    return false;
                ++_index;
                if (_index == _q._scope)
                {
                    _index   = -2;
                    _current = default;
                    return false;
                }
                _current = _q._array[_q._head + _index];
                return true;
            });
        }
        void IEnumerator.Reset()
        {
            _index   = -1;
            _current = default;
        }
    }
}

DynamicLimitedList.cs

Concurrent Non-Concurrent Limited List

using System;
using System.Collections;
using System.Collections.Generic;
[Serializable]
public class DynamicLimitedList<T> : MonitorActionFunc, IEnumerable<T>
{
    private volatile T[] _array;
    private volatile int _count;
    private volatile int _maxSize;
    public DynamicLimitedList(int maxsize)
    {
        _array   = new T[maxsize];
        _maxSize = maxsize;
    }
    public int MaxSize
    {
        get
        {
            var tmpThis = this;
            return tmpThis.Lock(tmpThis, () =>
            {
                return _maxSize;
            });
        }
    }
    public int Count
    {
        get
        {
            var tmpThis = this;
            return tmpThis.Lock(tmpThis, () =>
            {
                return _count;
            });
        }
    }
    public T this[int index]
    {
        get
        {
            var tmpThis = this;
            return tmpThis.Lock(tmpThis, () =>
            {
                if (index > _array.Length - 1)
                    throw new Exception($"Index {index} is out of range {_array.Length - 1}");
                return _array[index];
            });
        }
        set
        {
            var tmpThis = this;
            tmpThis.Lock(tmpThis, () =>
            {
                if (index > _array.Length - 1)
                    throw new Exception($"Index {index} is out of range {_array.Length - 1}");
                if (index < _maxSize)
                {
                    _array[index] = value;
                    _count++;
                    if (_count > _maxSize)
                        _count = _maxSize;
                }
            });
        }
    }
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public IEnumerator<T> GetEnumerator()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            return GetEnum();
        });
    }
    private IEnumerator<T> GetEnum()
    {
        var array = _array;
        var count = Count;
        for (var i = 0; i < count; i++)
            yield return array[i];
    }
    public void Add(T value)
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            if (_count == _maxSize)
            {
                LeftShift();
                _array[_maxSize - 1] = value;
            }
            else
            {
                _array[_count] = value;
                _count++;
            }
        });
    }
    private void LeftShift()
    {
        var TArray = new T[_maxSize];
        Array.Copy(_array, 1, TArray, 0, _maxSize - 1);
        _array = TArray;
    }
    public void Clear()
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            _array = new T[_maxSize];
            _count = 0;
        });
    }
    public bool Contains(T item)
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var size             = _maxSize;
            var equalityComparer = EqualityComparer<T>.Default;
            while (size-- > 0)
                if (_array[size] != null && equalityComparer.Equals(_array[size], item))
                    return true;
            return false;
        });
    }
    public T[] ToArray()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            var objArray = new T[_maxSize];
            Array.Copy(_array, 0, objArray, 0, _maxSize);
            return objArray;
        });
    }
    public List<T> ToList()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            return new List<T>(_array);
        });
    }
    public HashSet<T> ToHashSet()
    {
        var tmpThis = this;
        return tmpThis.Lock(tmpThis, () =>
        {
            return new HashSet<T>(_array);
        });
    }
    public void CopyTo(T[] array)
    {
        var tmpThis = this;
        tmpThis.Lock(tmpThis, () =>
        {
            Array.Copy(_array, 0, array, 0, _maxSize);
        });
    }
}

DynamicArray.cs

Use Concurrently or Non-Concurrently

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

[Serializable]
public class DynamicArray<T> : IEnumerable<T>
{
    private volatile T[]               _array;
    private volatile MonitorActionFunc _maf;
    public volatile  int               Count;
    public DynamicArray(int cap)
    {
        Count  = 0;
        _array = new T[cap];
        _maf   = new MonitorActionFunc();
    }
    public DynamicArray(IEnumerable<T> collection)
    {
        var enumerable = collection as T[] ?? collection.ToArray();
        Count  = enumerable.Length;
        _array = new T[Count];
        Array.Copy(enumerable, 0, _array, 0, Count);
        _maf = new MonitorActionFunc();
    }
    public int Length
    {
        get
        {
            var tmpThis = this;
            return tmpThis._maf.Lock(tmpThis, () => _array.Length);
        }
    }
    public T this[int index]
    {
        get
        {
            var array   = _array;
            var tmpThis = this;
            return tmpThis._maf.Lock(tmpThis, () =>
            {
                if (index > array.Length)
                    throw new Exception("Error: Index out of range.");
                return array[index];
            });
        }
        set
        {
            var tmpThis = this;
            tmpThis._maf.Lock(tmpThis, () =>
            {
                if (index > _array.Length)
                    throw new Exception("Error: Index out of range.");
                _array[index] = value;
            });
        }
    }
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public void Resize(int newSize)
    {
        var tmpThis = this;
        tmpThis._maf.Lock(tmpThis, () =>
        {
            Array.Resize(ref _array, newSize);
        });
    }
    public void Add(T item)
    {
        var tmpThis = this;
        tmpThis._maf.Lock(tmpThis, () =>
        {
            if (Count >= _array.Length)
                throw new Exception("Item exceeds array length.");
            _array[Count] = item;
            Interlocked.Increment(ref Count);
        });
    }
    public void AddRange(IEnumerable<T> collection)
    {
        var enumerable = collection as T[] ?? collection.ToArray();
        Count  = enumerable.Length;
        _array = new T[Count];
        Array.Copy(enumerable, 0, _array, 0, Count);
    }
    public T[] ToArray()
    {
        var tmpThis = this;
        return tmpThis._maf.Lock(tmpThis, () =>
        {
            var newtArray = new T[Count];
            Array.Copy(_array, 0, newtArray, 0, Count);
            return newtArray;
        });
    }
    public void Clean()
    {
        var tmpThis = this;
        tmpThis._maf.Lock(tmpThis, () =>
        {
            var newtArray = new T[Count];
            Array.Copy(_array, 0, newtArray, 0, Count);
            _array = newtArray;
        });
    }
    public void Clear()
    {
        var tmpThis = this;
        tmpThis._maf.Lock(tmpThis, () =>
        {
            Array.Clear(_array, 0, Count);
            Count = 0;
        });
    }
    public long IndexOf(T item)
    {
        var tmpThis = this;
        return tmpThis._maf.Lock(tmpThis, () => Array.IndexOf(_array, item, 0));
    }
    public IEnumerator<T> GetEnumerator()
    {
        var tmpThis = this;
        return tmpThis._maf.Lock(tmpThis, () =>
        {
            return GetEnum();
        });
    }
    private IEnumerator<T> GetEnum()
    {
        var array = _array;
        var count = Count;
        for (var i = 0; i < count; i++)
            yield return array[i];
    }
}

DynHashSet32n.cs

Dynamic Concurrent Hash Set 32 Bit

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
/// <summary>
///     Modified from ConcurrentDictionary. 20% faster than ConcurrentDictionary
/// </summary>
/// <typeparam name="T"></typeparam>
[DebuggerTypeProxy(typeof(HashSetDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class DynHashSet32n<T> : ConcurrencyCheck, IReadOnlyCollection<T>, ICollection<T>
{
    private readonly IEqualityComparer<T> _comparer;
    private readonly bool                 _growLockArray;
    private          int                  _budget;
    private volatile Tables               _tables;
    private volatile int                  grows;
    public DynHashSet32n() : this(DefaultConcurrencyLevel, 1048576, true, null)
    {
    }
    public DynHashSet32n(int capacity) : this(DefaultConcurrencyLevel, capacity, false, null)
    {
    }
    public DynHashSet32n(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, false, null)
    {
    }
    public DynHashSet32n(IEnumerable<T> collection) : this(collection, null)
    {
    }
    public DynHashSet32n(IEqualityComparer<T> comparer) : this(DefaultConcurrencyLevel, 1048576, true, comparer)
    {
    }
    public DynHashSet32n(IEnumerable<T> collection, IEqualityComparer<T> comparer) : this(comparer)
    {
        if (collection == null)
            throw new Exception("Collection is null.");
        InitializeFromCollection(collection);
    }
    public DynHashSet32n(int concurrencyLevel, IEnumerable<T> collection, IEqualityComparer<T> comparer) : this(concurrencyLevel, 1048576, false, comparer)
    {
        if (collection == null)
            throw new Exception("Collection is null.");
        InitializeFromCollection(collection);
    }
    public DynHashSet32n(int concurrencyLevel, int capacity, IEqualityComparer<T> comparer) : this(concurrencyLevel, capacity, false, comparer)
    {
    }
    private DynHashSet32n(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<T> comparer)
    {
        if (concurrencyLevel < 1)
            throw new Exception("Concurrency Level needs to be 1 or higher.");
        if (capacity < 0)
            throw new Exception("Capacity needs to be a positive number");
        if (capacity < concurrencyLevel)
            capacity = concurrencyLevel;
        var locks = new object[concurrencyLevel];
        for (var i = 0; i < locks.Length; i++)
            locks[i] = new object();
        var countPerLock = new int[locks.Length];
        var buckets      = new Node[capacity];
        _tables        = new Tables(buckets, locks, countPerLock);
        _growLockArray = growLockArray;
        _budget        = buckets.Length / locks.Length;
        _comparer      = comparer ?? EqualityComparer<T>.Default;
    }
    private static int DefaultConcurrencyLevel => Environment.ProcessorCount;
    public bool IsEmpty
    {
        get
        {
            var acquiredLocks = 0;
            try
            {
                AcquireAllLocks(ref acquiredLocks);
                if (_tables.CountPerLock.Any(t => t != 0))
                    return false;
            }
            finally
            {
                ReleaseLocks(0, acquiredLocks);
            }
            return true;
        }
    }
    public T this[int index]
    {
        get
        {
            if (index > Count)
                throw new Exception($"Getter: Index out of bounds {index} must be less than {Count}");
            return _tables.Buckets[index].Item;
        }
    }
    public void Clear()
    {
        var locksAcquired = 0;
        try
        {
            AcquireAllLocks(ref locksAcquired);
            var nTables = new Tables(new Node[1048576], _tables.Locks, new int[_tables.CountPerLock.Length]);
            _tables = nTables;
            _budget = Math.Max(1, nTables.Buckets.Length / nTables.Locks.Length);
        }
        finally
        {
            ReleaseLocks(0, locksAcquired);
        }
    }
    public bool Contains(T item)
    {
        if (item == null) return false;
        var hashcode     = _comparer.GetHashCode(item);
        var tables       = _tables;
        var bucketNumber = (hashcode & int.MaxValue) % tables.Buckets.Length;
        var current      = Volatile.Read(ref tables.Buckets[bucketNumber]);
        while (current != null)
        {
            if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
                return true;
            current = current.Next;
        }
        return false;
    }
    void ICollection<T>.Add(T item)
    {
        Add(item);
    }
    bool ICollection<T>.IsReadOnly => false;
    void ICollection<T>.CopyTo(T[] array, int arrayIndex)
    {
        if (array == null)
            throw new Exception("The array is null.");
        if (arrayIndex < 0)
            throw new Exception("The array index is out of range.");
        var locksAcquired = 0;
        try
        {
            AcquireAllLocks(ref locksAcquired);
            var count = 0;
            for (var i = 0; i < _tables.Locks.Length && count >= 0; i++)
                count += _tables.CountPerLock[i];
            if (array.Length - count < arrayIndex || count < 0)
                throw new Exception("The index is equal to or greater than the length of the array.");
            CopyTo(array, arrayIndex);
        }
        finally
        {
            ReleaseLocks(0, locksAcquired);
        }
    }
    bool ICollection<T>.Remove(T item)
    {
        return TryRemove(item);
    }
    public int Count
    {
        get
        {
            var count         = 0;
            var acquiredLocks = 0;
            try
            {
                AcquireAllLocks(ref acquiredLocks);
                count += _tables.CountPerLock.Sum();
            }
            finally
            {
                ReleaseLocks(0, acquiredLocks);
            }
            return count;
        }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public IEnumerator<T> GetEnumerator()
    {
        var buckets = _tables.Buckets;
        for (var i = 0; i < buckets.Length; i++)
        {
            var current = Volatile.Read(ref buckets[i]);
            while (current != null)
            {
                yield return current.Item;
                current = current.Next;
            }
        }
    }
    private void InitializeFromCollection(IEnumerable<T> collection)
    {
        foreach (var item in collection)
        {
            if (item == null)
                throw new Exception("Item in collection is null.");
            if (!AddInternal(item, false))
                throw new Exception("Source Contains Duplicates.");
        }
        if (_budget != 0)
            return;
        _budget = _tables.Buckets.Length / _tables.Locks.Length;
    }
    public bool Add(T item)
    {
        return AddInternal(item, true);
    }
    public bool TryRemove(T item)
    {
        var hashcode = _comparer.GetHashCode(item);
        while (true)
        {
            var tables = _tables;
            GetBucketAndlockNumber(hashcode, out var bucketNumber, out var lockNumber, tables.Buckets.Length, tables.Locks.Length);
            if (CheckState())
            {
                lock (tables.Locks[lockNumber])
                {
                    if (tables != _tables)
                        continue;
                    Node previous = null;
                    for (var current = tables.Buckets[bucketNumber]; current != null; current = current.Next)
                    {
                        if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
                        {
                            if (previous == null)
                                Volatile.Write(ref tables.Buckets[bucketNumber], current.Next);
                            else
                                previous.Next = current.Next;
                            tables.CountPerLock[lockNumber]--;
                            return true;
                        }
                        previous = current;
                    }
                }
            }
            else
            {
                if (tables != _tables)
                    continue;
                Node previous = null;
                for (var current = tables.Buckets[bucketNumber]; current != null; current = current.Next)
                {
                    if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
                    {
                        if (previous == null)
                            Volatile.Write(ref tables.Buckets[bucketNumber], current.Next);
                        else
                            previous.Next = current.Next;
                        tables.CountPerLock[lockNumber]--;
                        return true;
                    }
                    previous = current;
                }
            }
            return false;
        }
    }
    private bool AddInternal(T item, bool acquireLock)
    {
        var hashcode = _comparer.GetHashCode(item);
        while (true)
        {
            var tables = _tables;
            GetBucketAndlockNumber(hashcode, out var bucketNumber, out var lockNumber, tables.Buckets.Length, tables.Locks.Length);
            var resize    = false;
            var lockTaken = false;
            try
            {
                if (acquireLock && CheckState())
                    Monitor.Enter(tables.Locks[lockNumber], ref lockTaken);
                if (tables != _tables)
                    continue;
                for (var node = tables.Buckets[bucketNumber]; node != null; node = node.Next)
                    if (hashcode == node.Hashcode && _comparer.Equals(node.Item, item))
                        return false;
                Volatile.Write(ref tables.Buckets[bucketNumber], new Node(item, hashcode, tables.Buckets[bucketNumber]));
                checked
                {
                    tables.CountPerLock[lockNumber]++;
                }
                if (tables.CountPerLock[lockNumber] > _budget)
                    resize = true;
            }
            finally
            {
                if (lockTaken && CheckState())
                    Monitor.Exit(tables.Locks[lockNumber]);
            }
            if (resize)
                GrowTable(tables);
            return true;
        }
    }
    private static void GetBucketAndlockNumber(int hashcode, out int bucketNumber, out int lockNumber, int bucketCount, int lockCount)
    {
        bucketNumber = (hashcode & int.MaxValue) % bucketCount;
        lockNumber   = bucketNumber              % lockCount;
    }
    private void GrowTable(Tables tables)
    {
        var locksAcquired = 0;
        try
        {
            grows++;
            AcquireLocks(0, 1, ref locksAcquired);
            if (tables != _tables)
                return;
            var approxCount = tables.CountPerLock.Aggregate<int, long>(0, (current, t) => current + t);
            if (approxCount < tables.Buckets.Length / 4)
            {
                _budget = 2 * _budget;
                if (_budget < 0)
                    _budget = int.MaxValue;
                return;
            }
            var nLength      = 0;
            var maxTableSize = false;
            try
            {
                checked
                {
                    nLength = tables.Buckets.Length * 2 + 1;
                    while (nLength % 3 == 0 || nLength % 5 == 0 || nLength % 7 == 0)
                        nLength += 2;
                    if (nLength > int.MaxValue - 0x100000)
                        maxTableSize = true;
                }
            }
            catch (OverflowException)
            {
                maxTableSize = true;
            }
            if (maxTableSize)
            {
                nLength = int.MaxValue - 0x100000;
                _budget = int.MaxValue;
            }
            AcquireLocks(1, tables.Locks.Length, ref locksAcquired);
            var nLocks = tables.Locks;
            if (_growLockArray && tables.Locks.Length < 1024)
            {
                nLocks = new object[tables.Locks.Length * 2];
                Array.Copy(tables.Locks, 0, nLocks, 0, tables.Locks.Length);
                for (var i = tables.Locks.Length; i < nLocks.Length; i++)
                    nLocks[i] = new object();
            }
            var nBuckets      = new Node[nLength];
            var nCountPerLock = new int[nLocks.Length];
            foreach (var t in tables.Buckets)
            {
                var current = t;
                while (current != null)
                {
                    var next = current.Next;
                    GetBucketAndlockNumber(current.Hashcode, out var nbucketNumber, out var newlockNumber, nBuckets.Length, nLocks.Length);
                    nBuckets[nbucketNumber] = new Node(current.Item, current.Hashcode, nBuckets[nbucketNumber]);
                    checked
                    {
                        nCountPerLock[newlockNumber]++;
                    }
                    current = next;
                }
            }
            _budget = Math.Max(1, nBuckets.Length / nLocks.Length);
            _tables = new Tables(nBuckets, nLocks, nCountPerLock);
        }
        finally
        {
            ReleaseLocks(0, locksAcquired);
        }
    }
    private void AcquireAllLocks(ref int locksAcquired)
    {
        if (CheckState())
        {
            AcquireLocks(0, 1,                    ref locksAcquired);
            AcquireLocks(1, _tables.Locks.Length, ref locksAcquired);
        }
    }
    private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
    {
        if (CheckState())
        {
            var locks = _tables.Locks;
            for (var i = fromInclusive; i < toExclusive; i++)
            {
                var lockTaken = false;
                try
                {
                    Monitor.Enter(locks[i], ref lockTaken);
                }
                finally
                {
                    if (lockTaken)
                        locksAcquired++;
                }
            }
        }
    }
    private void ReleaseLocks(int fromInclusive, int toExclusive)
    {
        if (CheckState())
            for (var i = fromInclusive; i < toExclusive; i++)
                Monitor.Exit(_tables.Locks[i]);
    }
    private void CopyTo(T[] array, int index)
    {
        var buckets = _tables.Buckets;
        foreach (var t in buckets)
            for (var current = t; current != null; current = current.Next)
            {
                array[index] = current.Item;
                index++;
            }
    }
    public T[] ToArray()
    {
        var locksAcquired = 0;
        try
        {
            AcquireAllLocks(ref locksAcquired);
            var length = 0;
            var index  = 0;
            while (index < _tables.Locks.Length)
            {
                checked
                {
                    length += _tables.CountPerLock[index];
                }
                checked
                {
                    ++index;
                }
            }
            if (length == 0)
                return Array.Empty<T>();
            var array = new T[length];
            CopyTo(array, 0);
            return array;
        }
        finally
        {
            ReleaseLocks(0, locksAcquired);
        }
    }
    private class Tables
    {
        public readonly Node[]   Buckets;
        public readonly object[] Locks;
        public volatile int[]    CountPerLock;
        public Tables(Node[] buckets, object[] locks, int[] countPerLock)
        {
            Buckets      = buckets;
            Locks        = locks;
            CountPerLock = countPerLock;
        }
    }
    private class Node
    {
        public readonly int  Hashcode;
        public readonly T    Item;
        public volatile Node Next;
        public Node(T item, int hashcode, Node next)
        {
            Item     = item;
            Hashcode = hashcode;
            Next     = next;
        }
    }
}

DynArrayStruct32.cs

Dynamic Concurrent Generic Array Structure 32 Bit

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualBasic.Devices;
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public struct DynArrayStruct32<T> : IEnumerable<T>
{
    public const     int               ShiftCount  = 20;
    public const     int               Granularity = 1 << ShiftCount;
    private volatile Table             _table;
    public volatile  T[][]             Arrays;
    public volatile  int               MaximumNumberOfArrays;
    private volatile MonitorActionFunc maf;
    public DynArrayStruct32(long size)
    {
        if (size < Granularity)
            size = Granularity;
        try
        {
            maf                         = new MonitorActionFunc();
            _table                      = new Table();
            MaximumNumberOfArrays       = (int) (new ComputerInfo().AvailablePhysicalMemory / Granularity);
            _table.NumberOfActiveArrays = (int) ((size + (Granularity - 1))                 / Granularity);
            var val = (long) _table.NumberOfActiveArrays                                    * Granularity;
            _table.Length = Interlocked.Read(ref val);
            Arrays        = new T[MaximumNumberOfArrays][];
            for (var i = 0; i < _table.NumberOfActiveArrays; ++i)
                Arrays[i] = new T[Granularity];
        }
        catch (Exception ex)
        {
            throw new Exception($"'Initialize:DynArray' Exception: {ex.Message}");
        }
    }
    public DynArrayStruct32(IEnumerable<T> collection)
    {
        try
        {
            maf                   = new MonitorActionFunc();
            _table                = new Table();
            MaximumNumberOfArrays = (int) (new ComputerInfo().AvailablePhysicalMemory / Granularity);
            var size = Granularity;
            _table.NumberOfActiveArrays = (size + (Granularity - 1)) / Granularity;
            var val = (long) _table.NumberOfActiveArrays * Granularity;
            _table.Length = Interlocked.Read(ref val);
            Arrays        = new T[MaximumNumberOfArrays][];
            for (var i = 0; i < _table.NumberOfActiveArrays; ++i)
                Arrays[i] = new T[Granularity];
        }
        catch (Exception ex)
        {
            throw new Exception($"'Initialize:DynArray' Exception: {ex.Message}");
        }
        foreach (var item in collection)
            Add(item);
    }
    public long Count
    {
        get
        {
            var tmpThis = this;
            return tmpThis.maf.Lock(tmpThis, () =>
            {
                return tmpThis._table.Count;
            });
        }
    }
    public long Length
    {
        get
        {
            var tmpThis = this;
            return tmpThis.maf.Lock(tmpThis, () =>
            {
                return tmpThis._table.Length;
            });
        }
    }
    public T this[long index]
    {
        get
        {
            var tmpThis = this;
            return tmpThis.maf.Lock(tmpThis, () =>
            {
                if (index >= tmpThis._table.Length)
                    throw new Exception($"Getter: Index out of bounds, Index: '{index}' must be less than the Length: '{tmpThis.Length}'.");
                return tmpThis.Arrays[index >> ShiftCount][index & (Granularity - 1)];
            });
        }
        set
        {
            var tmpThis = this;
            tmpThis.maf.Lock(tmpThis, () =>
            {
                if (index + 1 > tmpThis._table.Length)
                    tmpThis.EnsureSize();
                tmpThis.Arrays[index >> ShiftCount][index & (Granularity - 1)] = value;
                tmpThis._table.Count++;
            });
        }
    }
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return new Enumerator(this);
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator(this);
    }
    public void Add(T Item)
    {
        var tmpThis = this;
        tmpThis.maf.Lock(tmpThis, () =>
        {
            if (tmpThis._table.Count + 1 > tmpThis._table.Length)
                tmpThis.EnsureSize();
            tmpThis.Arrays[tmpThis._table.Count >> ShiftCount][tmpThis._table.Count & (Granularity - 1)] = Item;
            tmpThis._table.Count++;
        });
    }
    public void AddRange(IEnumerable<T> collection)
    {
        var tmpThis = this;
        tmpThis.maf.Lock(tmpThis, () =>
        {
            foreach (var item in collection)
                tmpThis.Add(item);
        });
    }
    public Enumerator GetEnumerator()
    {
        return new Enumerator(this);
    }
    private void EnsureSize()
    {
        try
        {
            _table.NumberOfActiveArrays++;
            if (_table.NumberOfActiveArrays >= MaximumNumberOfArrays)
                throw new Exception($"Number of active arrays {_table.NumberOfActiveArrays} cannot meet or exceed the maximum number of arrays {MaximumNumberOfArrays} allowed.");
            var val = (long) _table.NumberOfActiveArrays * Granularity;
            _table.Length                           = Interlocked.Read(ref val);
            Arrays[_table.NumberOfActiveArrays - 1] = new T[Granularity];
        }
        catch (Exception ex)
        {
            throw new Exception($"'EnsureSize:DynArray' Exception: {ex.Message}");
        }
    }
    public void Clear()
    {
        var tmpThis = this;
        tmpThis.maf.Lock(tmpThis, () =>
        {
            for (var a = 0L; a < tmpThis._table.NumberOfActiveArrays; a++)
                Array.Clear(tmpThis.Arrays[a], 0, Granularity);
            tmpThis._table.Count = 0;
        });
    }
    public long IndexOf(T item)
    {
        var tmpThis = this;
        return tmpThis.maf.Lock(tmpThis, () =>
        {
            var i = 0L;
            for (; i < tmpThis._table.NumberOfActiveArrays; i++)
            {
                var pos = Array.IndexOf(tmpThis.Arrays[i], item, 0);
                if (pos != -1)
                    return i * Granularity + pos;
            }
            return -1;
        });
    }
    public DynArrayStruct32<T> Copy(int newsize)
    {
        var tmpThis = this;
        return tmpThis.maf.Lock(tmpThis, () =>
        {
            var temp = new DynArrayStruct32<T>(newsize);
            for (var a = 0L; a < tmpThis._table.NumberOfActiveArrays; a++)
                Array.Copy(tmpThis.Arrays[a], temp.Arrays[a], Granularity);
            return temp;
        });
    }
    public DynArrayStruct32<T> CopyOrInsert(T item, int newsize)
    {
        var tmpThis = this;
        return tmpThis.maf.Lock(tmpThis, () =>
        {
            if (newsize > tmpThis._table.Length)
            {
                var temp = new DynArrayStruct32<T>(newsize);
                for (var a = 0L; a < tmpThis._table.NumberOfActiveArrays; a++)
                    Array.Copy(tmpThis.Arrays[a], temp.Arrays[a], Granularity);
                temp._table.Count = tmpThis.Count;
                temp.Add(item);
                return temp;
            }
            tmpThis.Add(item);
            return tmpThis;
        });
    }
    public void FromArray(T[][] array)
    {
        var tmpThis = this;
        tmpThis.maf.Lock(tmpThis, () =>
        {
            tmpThis._table.NumberOfActiveArrays = array.GetUpperBound(0) + 1;
            var val = (long) tmpThis._table.NumberOfActiveArrays * Granularity;
            tmpThis._table.Length = Interlocked.Read(ref val);
            tmpThis.Arrays        = new T[tmpThis._table.NumberOfActiveArrays][];
            for (var i = 0; i < tmpThis._table.NumberOfActiveArrays; ++i)
                tmpThis.Arrays[i] = new T[Granularity];
            for (var a = 0L; a < tmpThis._table.NumberOfActiveArrays; a++)
                Array.Copy(array[a], tmpThis.Arrays[a], Granularity);
        });
    }
    public T[][] ToArray()
    {
        var tmpThis = this;
        return tmpThis.maf.Lock(tmpThis, () =>
        {
            var ta = new T[tmpThis._table.NumberOfActiveArrays][];
            for (var i = 0; i < tmpThis._table.NumberOfActiveArrays; ++i)
                ta[i] = new T[Granularity];
            for (var a = 0L; a < tmpThis._table.NumberOfActiveArrays; a++)
                Array.Copy(tmpThis.Arrays[a], ta[a], Granularity);
            return ta;
        });
    }
    public T[] ToArray32()
    {
        var tmpThis = this;
        return tmpThis.maf.Lock(tmpThis, () =>
        {
            if (tmpThis.Count >= uint.MaxValue)
                throw new Exception("Too many elements to cast to a 32Bit array.");
            var array = new T[tmpThis.Count];
            var cnt   = 0l;
            for (var a = 0L; a < tmpThis._table.NumberOfActiveArrays && cnt < uint.MaxValue; a++, cnt += Granularity)
                Array.Copy(tmpThis.Arrays[a], 0, array, a * Granularity, Granularity);
            return array;
        });
    }
    public (int l, int r) BoundsFromIndex(int index)
    {
        var l = index >> ShiftCount;
        var r = index & (Granularity - 1);
        return (r, r);
    }
    public int IndexFromBounds(int l, int r)
    {
        return l * Granularity + r;
    }
    private class Table
    {
        public          long Count;
        public          long Length;
        public volatile int  NumberOfActiveArrays;
    }
    [Serializable]
    public class Enumerator : IEnumerator<T>
    {
        private readonly DynArrayStruct32<T> _array;
        private volatile eTable              _eTable = new eTable();
        internal Enumerator(DynArrayStruct32<T> array)
        {
            _array         = array;
            _eTable._index = 0;
            Current        = default;
        }
        public T Current
        {
            get;
            private set;
        }
        object IEnumerator.Current
        {
            get
            {
                return _array.maf.Lock(this, () =>
                {
                    if (_eTable._index == _array._table.Count + 1)
                        throw new Exception($"Enumerator out of range: {_eTable._index}");
                    return Current;
                });
            }
        }
        public void Dispose()
        {
        }
        public bool MoveNext()
        {
            return _array.maf.Lock(this, () =>
            {
                for (; _eTable._index < _array._table.Count; ++_eTable._index)
                    if (_eTable._index < _array._table.Count || _eTable._index == 0)
                    {
                        Current = _array[_eTable._index];
                        ++_eTable._index;
                        return true;
                    }
                _eTable._index = _array._table.Count + 1;
                Current        = default;
                return false;
            });
        }
        void IEnumerator.Reset()
        {
            _eTable._index = 0;
            Current        = default;
        }
        private class eTable
        {
            public long _index;
        }
    }
}