Check and Store Concurrency Usage
Updated: Dec-25,2020
using System; using System.Diagnostics; using System.Threading; public class ConcurrencyCheck { public volatile ConcurrencyInfo ConcurrencyInformation = new ConcurrencyInfo(); private static int ProcessorCount => Environment.ProcessorCount; public bool OverrideAutoConcurrency { get; set; } public bool QuickCheck { get; set; } = false; public bool UsingConcurrency { get; private set; } public bool CheckState() { if (OverrideAutoConcurrency) return false; if (QuickCheck && ConcurrencyInformation.Calls > ProcessorCount && ConcurrencyInformation.LockState == 0) return false; if (ConcurrencyInformation.StatusThreadId != Thread.CurrentThread.ManagedThreadId) { ConcurrencyInformation.StatusThreadId = Thread.CurrentThread.ManagedThreadId; ConcurrencyInformation.Add(ConcurrencyInformation.StatusThreadId); } if (ConcurrencyInformation.LockState == 1) return true; if (ConcurrencyInformation.BeginningThreadId == 0 && ConcurrencyInformation.LockState == 0 && Thread.CurrentThread.ManagedThreadId != 0) ConcurrencyInformation.BeginningThreadId = Thread.CurrentThread.ManagedThreadId; if (ConcurrencyInformation.LockState == 0) if (ConcurrencyInformation.BeginningThreadId != Thread.CurrentThread.ManagedThreadId) { ConcurrencyInformation.LockState = 1; UsingConcurrency = true; return true; } Interlocked.Increment(ref ConcurrencyInformation.Calls); return false; } [DebuggerDisplay("UniqueThreadIds = {ActiveThreads}")] public class ConcurrencyInfo { public volatile int ActiveThreads; public volatile int BeginningThreadId; public volatile int Calls; public volatile int LockState; public volatile int StatusThreadId; public volatile bool[] UniqueThreadIds = new bool[32768]; public void Add(int value) { if (!UniqueThreadIds[value]) { UniqueThreadIds[value] = true; Interlocked.Increment(ref ActiveThreads); return; } } } }