.NET Framework 2.0 Performance Inspection Questions - Threading

From Guidance Share

Revision as of 05:15, 21 December 2007; JD (Talk | contribs)
(diff) ←Older revision | Current revision | Newer revision→ (diff)
Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, Rico Mariani, and Alex Mackman



Contents

Do You Create Additional Threads?

You should generally avoid creating threads, particularly in server-side code — use the CLR thread pool instead. In addition to the cost of creating the underlying operating system thread, frequently creating new threads can also lead to excessive context switching, memory allocation, and additional cleanup when the thread dies. Recycling threads within the thread pool generally leads to superior results.


Do You Call Thread.Suspend or Thread.Resume?

Use synchronization objects if you need to synchronize threads. Calling Thread.Suspend and Thread.Resume to synchronize the activities of multiple threads can cause deadlocks. Generally, Suspend and Resume should be used only in the context of debugging or profiling, and not at all for typical applications. Use synchronization objects such as ManualResetEvent objects if you need to synchronize threads.


Do You Use Volatile Fields?

Limit the use of the volatile keyword because volatile fields restrict the way the compiler reads and writes the contents of the fields. Volatile fields are not meant for ensuring thread safety.


Do You Execute Periodic Tasks?

If you require a single thread for periodic tasks, it is cheaper to have just one thread explicitly executing the periodic tasks and then sleeping until it needs to perform the task again. However, if you require multiple threads to execute periodic tasks for each new request, you should use the thread pool.


Use the Threading.Timer class to periodically schedule tasks. The Timer class uses the CLR thread pool to execute the code.


Note that a dedicated thread is more likely to get scheduled at the correct time than a pooled thread. This is because if all threads are busy, there could be a delay between the scheduled time of the background work and a worker thread becoming available. If there is a dedicated thread for the background work, a thread will be ready at the appointed time.

Personal tools