ConcurrencyCheck.cs

Check and Store Concurrency Usage

using System;
using System.Diagnostics;
using System.Threading;
public class ConcurrencyCheck
{
    public volatile ConcurrencyInfo concurrencyInfo = new ConcurrencyInfo();
    private         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 && concurrencyInfo.Calls > ProcessorCount && concurrencyInfo.LockState == 0)
            return false;
        if (concurrencyInfo.StatusThreadId != Thread.CurrentThread.ManagedThreadId)
        {
            concurrencyInfo.StatusThreadId = Thread.CurrentThread.ManagedThreadId;
            concurrencyInfo.Add(concurrencyInfo.StatusThreadId);
        }
        if (concurrencyInfo.LockState == 1)
            return true;
        if (concurrencyInfo.BeginningThreadId == 0 && concurrencyInfo.LockState == 0 && Thread.CurrentThread.ManagedThreadId != 0)
            concurrencyInfo.BeginningThreadId = Thread.CurrentThread.ManagedThreadId;
        if (concurrencyInfo.LockState == 0)
            if (concurrencyInfo.BeginningThreadId != Thread.CurrentThread.ManagedThreadId)
            {
                concurrencyInfo.LockState = 1;
                UsingConcurrency          = true;
                return true;
            }
        concurrencyInfo.Calls++;
        return false;
    }
    [DebuggerDisplay("UniqueThreadIds = {ActiveThreads}")]
    public class ConcurrencyInfo
    {
        public volatile int     ActiveThreads=1;
        public volatile int     BeginningThreadId;
        public volatile int     Calls;
        public volatile ulong[] ContextSwitches = new ulong[32768];
        public volatile int     LockState;
        public volatile int     StatusThreadId;
        public volatile int[]   UniqueThreadIds = new int[32768];
        public void Add(int value)
        {
            if (UniqueThreadIds[value] != value)
            {
                UniqueThreadIds[value] = value;
                ActiveThreads++;
                return;
            }
            ContextSwitches[value]++;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *