Created
January 12, 2021 14:16
-
-
Save mjs3339/d7a64753e8dc532cacee3eaa6e5d8a01 to your computer and use it in GitHub Desktop.
Check and Store Concurrency Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment