Don't create threads explicitly

Rule ND2500 .NET Framework Usage / System.Threading

Warns about methods instantiating System.Threading.Thread. Threads are costly (~200,000 cycles to create, ~100,000 to destroy, 1MB stack, 2,000-8,000 cycles per context switch): prefer letting the thread pool recycle threads.

How to fix

Use the Task Parallel Library (TPL), relying on the CLR thread pool, instead of creating threads. Introduction: https://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx TPL and the CLR v4 thread pool: http://www.danielmoth.com/Blog/New-And-Improved-CLR-4-Thread-Pool-Engine.aspx

Severity is Critical: creating threads can have severe consequences.

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Don't create threads explicitly</Name>
// <Id>ND2500:DontCreateThreadsExplicitly</Id>

warnif count > 0 from m in Application.Methods where 
  m.CreateA ("System.Threading.Thread".AllowNoMatch())
select new {
   m,
   Debt = 40.ToMinutes().ToDebt(),
   Severity = Severity.Critical
}

//<Expl>
// The *{0}* creates a *Thread* object.
// It's better to use the thread pool instead because threads 
// are expensive resources and can be challenging to manage effectively.
//</Expl>

//<Desc>
// Warns about methods instantiating *System.Threading.Thread*. Threads are
// costly (~200,000 cycles to create, ~100,000 to destroy, 1MB stack,
// 2,000-8,000 cycles per context switch): prefer letting the thread pool
// recycle threads.
//</Desc>

//<HowToFix>
// Use the **Task Parallel Library** *(TPL)*, relying on the CLR thread
// pool, instead of creating threads.
// Introduction: https://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx
// TPL and the CLR v4 thread pool:
// http://www.danielmoth.com/Blog/New-And-Improved-CLR-4-Thread-Pool-Engine.aspx
//
// Severity is **Critical**: creating threads can have severe consequences.
//</HowToFix>

.NET Framework Usage / System.Threading: all 6 items