Don't create threads explicitly
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.
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>
Open in the interactive Rules Explorer · All default rules
.NET Framework Usage / System.Threading: all 6 items
- Don't create threads explicitly ND2500
- Don't use dangerous threading methods ND2501
- Monitor TryEnter/Exit must be both called within the same method ND2502
- ReaderWriterLock AcquireLock/ReleaseLock must be both called within the same method ND2503
- Don't tag instance fields with ThreadStaticAttribute ND2504
- Method non-synchronized that read mutable states ND2505