Reader small image

You're reading from  Parallel Programming and Concurrency with C# 10 and .NET 6

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781803243672
Edition1st Edition
Right arrow
Author (1)
Alvin Ashcraft
Alvin Ashcraft
author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft

Right arrow

Chapter 3: Best Practices for Managed Threading

When building applications that leverage parallelism and concurrency, developers need to be aware of some best practices regarding integrating managed threading concepts. This chapter will assist in this capacity. We will cover important concepts such as working with static data, avoiding deadlocks, and exhausting managed resources. These are all areas that can lead to unstable applications and unexpected behavior.

In this chapter, you will learn the following concepts:

  • Handling static objects
  • Managing deadlocks and race conditions
  • Threading limits and other recommendations

By the end of this chapter, you will have the knowledge to avoid the most common managed threading pitfalls.

Technical requirements

To follow along with the examples in this chapter, the following software is recommended for Windows developers:

  • Visual Studio 2022 version 17.0 or later
  • .NET 6

While these are recommended, if you have .NET 6 installed, you can use your preferred editor. For example, Visual Studio 2022 for Mac on macOS 10.13 or later, JetBrains Rider, or Visual Studio Code will work just as well.

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/Parallel-Programming-and-Concurrency-with-C-sharp-10-and-.NET-6/tree/main/chapter03.

We will get started by discussing some best practices for handling static data in .NET.

Handling static objects

When working with static data in .NET, there are some important things to understand when it comes to managed threading.

Static data and constructors

One important item to understand about accessing static data from managed threads relates to constructors. Before a static member of any class can be accessed, its static constructor must first finish running. The runtime will block thread execution until the static constructor has run to ensure that all required initialization has finished.

If you are using static objects within your own code base, you will know which classes have static constructors and can control the complexity of the logic inside them. When the static data is outside of your control, inside a third-party library or .NET itself, things may not be so clear.

Let’s try a quick example to illustrate the potential delays that can be encountered in this scenario.

  1. Start by creating a new .NET console application in Visual...

Managing deadlocks and race conditions

As with many tools at a developer’s disposal, misusing features of managed threading can have adverse impacts on your applications at runtime. Deadlocks and race conditions are two scenarios that can be created because of multithreaded programming:

  • A deadlock happens when multiple threads are trying to lock the same resource and as a result, cannot continue executing.
  • Race conditions happen when multiple threads are proceeding toward updating a particular routine, and a correct outcome is dependent on the order in which they execute it.

Figure 3.2 – Two threads in contention for the same resources, causing a deadlock

First, let’s discuss deadlocks and some techniques for avoiding them.

Mitigating deadlocks

It is critical to avoid deadlocks in your applications. If one of the threads involved in a deadlock is the application’s UI thread, it will cause the application to...

Threading limits and other recommendations

So, it sounds like using multiple threads can really speed up your application’s performance. You should probably start replacing all your foreach loops with Parallel.ForEach loop and start calling all your services and helper methods on thread pool threads, right? Are there any limits and what are they? Well, when it comes to threading, there absolutely are limits.

The number of threads that can execute simultaneously is limited by the number of processors and processor cores on the system. There is no way around hardware limitations, as the CPU (or virtual CPU when running on a virtual machine) can only run so many threads. In addition, your application must share these CPUs with other processes running on the system. If your CPU has four cores, it is actively running five other applications, and your program is trying to execute a process with multiple threads, the system is not likely to accept more than one of your threads at...

Summary

In this chapter, we discussed some best practices to follow when working with managed threads in C# and .NET. We started by creating some examples of how to manage and process static data in a multithreaded application. The examples illustrated how to leverage locks, work with singletons, and how static constructors can impact performance when working with static data. Next, we explored some techniques for avoiding deadlocks and race conditions. Both pitfalls can be avoided if you design your algorithms to minimize the need for locking. Finally, we looked at some features of .NET that can adjust the limits of several parallel and thread pool operations.

At this point, you are well prepared to start using managed threads responsibly in your .NET projects. For some further reading on best practices with managed threading, you can check out some recommendations on Microsoft Docs: https://docs.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices.

...

Questions

  1. Which design pattern models how to create an object that only has one instance?
  2. What .NET attribute will cause a static field to have one instance per thread?
  3. What is a threading deadlock?
  4. Which method on the Monitor class can be used to specify a timeout when trying to access a locked resource?
  5. Which lightweight class can be used to lock value types for atomic operations?
  6. Which thread-safe operation can be used to add two integers?
  7. What option can be set on a Parallel.For or Parallel.ForEach loop to limit the number of threads used?
  8. How can you limit the number of threads used in a PLINQ query?
  9. What is the name of the method to find the current minimum thread values on the thread pool?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Parallel Programming and Concurrency with C# 10 and .NET 6
Published in: Aug 2022Publisher: PacktISBN-13: 9781803243672
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft