Framework-Specific Guidelines
Multithreading
Use synchronization domains. Avoid manual synchronization, because that often leads to deadlocks and race conditions.
Never call outside your synchronization domain.
Manage asynchronous call completion on a callback method. Do not wait, poll, or block for completion.
Always name your threads:
Thread currentThread = Thread.CurrentThread; string threadName = "Main UI Thread"; currentThread.Name = threadName;
The name is traced in the debugger Threads window, making debug sessions more productive.
Do not call
Suspend()
orResume()
on a thread.Do not call
Thread.Sleep()
, except in the following conditions:Thread.Sleep(0)
is an acceptable optimization technique to force a context switch.Thread.Sleep()
is acceptable in testing or simulation code.
Do not call
Thread.SpinWait()
.Do not call
Thread.Abort()
to terminate threads. Use a synchronization object instead to signal the thread to terminate.Avoid explicitly setting the thread priority to control execution. You can set the thread priority based on task semantics (such as
ThreadPriority.BelowNormal
for a screensaver).Do not read the value of the
ThreadState
property. UseThread.IsAlive()
to determine whether the thread is dead or alive.Do not rely on setting the thread type to background thread for application shutdown. Use a watchdog or other monitoring entity to deterministically kill threads.
Do not use the thread local storage unless thread affinity is guaranteed.
Do not call
Thread.MemoryBarrier() ...
Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.