High-Performance Programming in C# and .NET

Book description

Enhance your applications' performance using best practices for benchmarking, application profiling, asynchronous programming, designing responsive UIs, gRPC communication, and distributed applications

Key Features

  • Make the best use of performance enhancements in C# 10.0 and .NET 6
  • Boost application performance by identifying hardware bottlenecks and common performance pitfalls
  • Get to grips with best practices and techniques for improving the scalability of distributed systems

Book Description

Writing high-performance code while building an application is crucial, and over the years, Microsoft has focused on delivering various performance-related improvements within the .NET ecosystem. This book will help you understand the aspects involved in designing responsive, resilient, and high-performance applications with the new version of C# and .NET.

You will start by understanding the foundation of high-performance code and the latest performance-related improvements in C# 10.0 and .NET 6. Next, you'll learn how to use tracing and diagnostics to track down performance issues and the cause of memory leaks. The chapters that follow then show you how to enhance the performance of your networked applications and various ways to improve directory tasks, file tasks, and more. Later, you'll go on to improve data querying performance and write responsive user interfaces. You'll also discover how you can use cloud providers such as Microsoft Azure to build scalable distributed solutions. Finally, you'll explore various ways to process code synchronously, asynchronously, and in parallel to reduce the time it takes to process a series of tasks.

By the end of this C# programming book, you'll have the confidence you need to build highly resilient, high-performance applications that meet your customer's demands.

What you will learn

  • Use correct types and collections to enhance application performance
  • Profile, benchmark, and identify performance issues with the codebase
  • Explore how to best perform queries on LINQ to improve an application's performance
  • Effectively utilize a number of CPUs and cores through asynchronous programming
  • Build responsive user interfaces with WinForms, WPF, MAUI, and WinUI
  • Benchmark ADO.NET, Entity Framework Core, and Dapper for data access
  • Implement CQRS and event sourcing and build and deploy microservices

Who this book is for

This book is for software engineers, professional software developers, performance engineers, and application profilers looking to improve the speed of their code or take their skills to the next level to gain a competitive advantage. You should be a proficient C# programmer who can already put the language to good use and is also comfortable using Microsoft Visual Studio 2022.

Table of contents

  1. High-Performance Programming in C# and .NET
  2. Contributors
  3. About the author
  4. About the reviewers
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Download the color images
    6. Conventions used
    7. Get in touch
    8. Share Your Thoughts
  6. Part 1: High-Performance Code Foundation
  7. Chapter 1: Introducing C# 10.0 and .NET 6
    1. Technical requirements
      1. Obtaining and building the latest Roslyn compiler from the source code
    2. Overview of Microsoft .NET 6
      1. Moving to one unified platform
      2. Garbage collection
      3. Just-In-Time compiler
      4. Text-based processing
      5. Threading and asynchronous operations
      6. Collections and LINQ
      7. Networking and Blazor
      8. New performance-based APIs and analyzers
    3. Overview of C# 10.0
      1. Writing top-level programs
      2. Using init-only properties
      3. Using records
      4. Using the new pattern matching features
      5. Using new expressions with targeted types
      6. Using covariant returns
    4. Native compilation
      1. Performing native compilation of .NET Core applications
    5. Improving Windows Store performance
    6. Improving ASP.NET performance
    7. Summary
    8. Questions and exercises
    9. Further reading
  8. Chapter 2: Implementing C# Interoperability
    1. Technical requirements
    2. Using Platform Invocation (P/Invoke)
      1. Using unsafe and fixed code
      2. Exposing static entry points using P/Invoke
    3. Interacting with Python code
    4. Performing Component Object Model (COM) interoperability
      1. Reading data from an Excel spreadsheet
      2. Creating an Excel add-in
    5. Safely disposing of unmanaged code
    6. Summary
    7. Questions
      1. Further reading
  9. Chapter 3: Predefined Data Types and Memory Allocations
    1. Technical requirements
    2. Understanding the predefined .NET data types
      1. Understanding the predefined value types in C#
      2. Understanding the predefined reference types in C#
      3. Understanding static types
    3. Understanding the various types of memory used in C#
      1. The stack
      2. The heap
      3. Building a stack versus building a heap (example project)
      4. Choosing between a struct and a class
    4. Passing by value and passing by reference
      1. Building a pass-by-reference example program
    5. Boxing and unboxing
      1. Performing boxing
      2. Performing unboxing
    6. Summary
    7. Questions
    8. Further reading
  10. Chapter 4: Memory Management
    1. Technical requirements
    2. Object generations and avoiding memory issues
    3. Understanding long and short weak references
    4. Finalization
      1. Using finalization
    5. Implementing the IDisposable pattern
    6. Preventing memory leaks
      1. Understanding the dangers of using Marshal.ReleaseComObject
      2. How using events can be a source of memory leaks
    7. Summary
    8. Questions
    9. Further reading
  11. Chapter 5: Application Profiling and Tracing
    1. Technical requirements
    2. Understanding code metrics
      1. Application metrics
      2. Assembly metrics
      3. Namespace metrics
      4. Type metrics
      5. Method metrics
      6. Field metrics
    3. Performing static code analysis
    4. Generating and viewing memory dumps
    5. Viewing loaded modules
    6. Debugging your applications
    7. Using tracing and diagnostics tools
      1. Using the Visual Studio 2022 Performance Profiler
      2. Using JetBrains dotMemory
      3. Using JetBrains dotTrace
    8. Installing and using dotnet-counters
      1. Collecting data and saving it to a file for post-analysis
      2. Listing .NET processes that can be monitored
      3. Listing the available list of well-known .NET counters
      4. Monitoring a .NET process
    9. Tracking down and fixing a memory leak with dotMemory
    10. Finding the cause of a UI freeze with dotTrace
    11. Optimizing application performance and memory traffic with dotTrace
    12. Summary
    13. Questions
    14. Further reading
  12. Part 2: Writing High-Performance Code
  13. Chapter 6: The .NET Collections
    1. Technical requirements
    2. Understanding the different collection offerings
      1. The System.Collections namespace
      2. The System.Collections.Generic namespace
      3. The System.Collections.Concurrent namespace
      4. The System.Collections.Specialized namespace
      5. Creating custom collections
    3. Understanding Big O notation
      1. Choosing the right collection
    4. Setting up our sample database
    5. Deciding between interfaces and concrete classes
    6. Deciding between using arrays or collections
    7. Accessing objects using indexers
    8. Comparing IEnumerable and IEnumerator
    9. Database query performance
    10. Exploring the yield keyword
    11. Learning the difference between concurrency and parallelism
    12. Learning the difference between Equals() and ==
    13. Summary
    14. Questions
    15. Further reading
  14. Chapter 7: LINQ Performance
    1. Technical requirements
    2. Setting up a sample database
    3. Setting up our in-memory sample data
    4. Database query performance
    5. Getting the last value of a collection
    6. Avoid using the let keyword in LINQ queries
    7. Increasing Group By performance in LINQ queries
    8. Filtering lists
    9. Understanding closures
    10. Summary
    11. Questions
    12. Further reading
  15. Chapter 8: File and Stream I/O
    1. Technical requirements
    2. Understanding the various Windows file path formats
      1. Removing the maximum path length limitation using the registry
      2. Removing the maximum path length limitation using the group policy
    3. Considering improved I/O performance
      1. Moving files
      2. Calculating directory sizes
      3. Accessing files asynchronously
      4. Writing text to a file asynchronously
    4. Handling I/O operation exceptions
    5. Performing memory tasks efficiently
    6. Understanding local storage tasks
    7. Summary
    8. Questions
    9. Further reading
  16. Chapter 9: Enhancing the Performance of Networked Applications
    1. Technical requirements
    2. Understanding the network layers and protocols
      1. The TCP/IP model
      2. Writing an example email application with the TCP/IP model
    3. Improving web-based network traffic
      1. Recording your web-applications performance using Microsoft Edge
    4. High-performance communication using gRPC
      1. Programming a simple gRPC client/server application
      2. Programming a simple gRPC Blazor application
      3. The blank solution
    5. Optimizing internet resources
    6. Using pipelines for content streaming
      1. Writing and running a TCP server console application
      2. Writing and running a TCP client console application
    7. Caching resources in memory
    8. Summary
    9. Questions
    10. Further reading
  17. Chapter 10: Setting Up Our Database Project
    1. Technical requirements
    2. Setting up our database
    3. Setting up our database access project
      1. Writing the Properties class
      2. Writing the DatabaseSettings class
    4. Writing the SecretsManager
    5. Writing the Product class
    6. Writing the SqlCommandModel class
    7. Writing the SqlCommandParameterModel class
    8. Writing the AdoDotNet class
    9. Writing the EntityFrameworkCoreData class
    10. Writing the DapperDotNet class
    11. Summary
    12. Further reading
  18. Chapter 11: Benchmarking Relational Data Access Frameworks
    1. Technical requirements
    2. Benchmarking data insertion methods
    3. Benchmarking data selection methods
    4. Benchmarking data editing methods
    5. Benchmarking data deletion methods
    6. The benchmarking results and their analysis
    7. Summary
    8. Questions
    9. Further reading
  19. Chapter 12: Responsive User Interfaces
    1. Technical requirements
    2. Building a responsive UI with WinForms
      1. Enabling DPI awareness and long file path awareness
      2. Adding a splash screen that updates with loading progress
      3. Adding the increment count button and label
      4. Adding a table with paged data
      5. Running long-running tasks in the background
    3. Building a responsive UI with WPF
    4. Building a responsive UI with ASP.NET
      1. Implementing memory caching
      2. Implementing distributed caching
      3. Using AJAX to update part of the currently displayed page
      4. Implementing WebSockets
      5. Implementing a real-time chat application using SignalR
    5. Building responsive UIs with .NET MAUI
      1. Layouts
      2. Accessibility
      3. BlazorWebView
    6. Building a responsive UI with MAUI
    7. Building a responsive UI with WinUI 3
    8. Summary
    9. Questions
    10. Further reading
  20. Chapter 13: Distributed Systems
    1. Technical requirements
    2. Implementing the CQRS design pattern
    3. Implementing event sourcing
      1. Event sourcing example project
    4. Using Microsoft Azure for distributed systems
      1. Azure Functions
      2. Durable Azure Functions
      3. Containers and serverless
    5. Managing your cloud infrastructure with Pulumi
    6. Performance considerations for distributed computing
    7. Summary
    8. Questions
    9. Further reading
  21. Part 3: Threading and Concurrency
  22. Chapter 14: Multi-Threaded Programming
    1. Technical requirements
    2. Understanding threads and threading
    3. Creating threads and using parameters
    4. Pausing and interrupting threads
    5. Destroying and canceling threads
    6. Scheduling threads
    7. Thread synchronization and locking
    8. Summary
    9. Questions
    10. Further reading
  23. Chapter 15: Parallel Programming
    1. Technical requirements
    2. Using the Task Parallel Library (TPL)
    3. Using Parallel LINQ (PLINQ)
      1. Programming parallel data structures
    4. Benchmarking with BenchmarkDotNet
    5. Using lambda expressions with TPL and LINQ
    6. Parallel debugging and profiling tools
      1. The Parallel Stacks window
      2. The Tasks window
      3. The Concurrency Visualizer
    7. Summary
    8. Questions
    9. Further reading
  24. Chapter 16: Asynchronous Programming
    1. Technical requirements
    2. Understanding the TAP model
      1. Naming, parameters, and return types
      2. Initiating asynchronous operations
      3. Exceptions
      4. Optional cancellation
      5. Optional Progress Reporting
    3. async, await, and Task
    4. Benchmarking GetAwaiter.GetResult(), .Result, and .Wait for both Task and ValueTask
    5. Using async, await, and WhenAll
    6. Canceling asynchronous operations
    7. Writing files asynchronously
    8. Reading files asynchronously
    9. Summary
    10. Questions
    11. Further reading
  25. Assessments
    1. Chapter 1, Introducing C# 10.0 and .NET 6
    2. Chapter 2, Implementing C# Interoperability
    3. Chapter 3, Predefined Data Types and Memory Allocations
    4. Chapter 4, Memory Management
    5. Chapter 5, Application Profiling and Tracing
    6. Chapter 6, The .NET Collections
    7. Chapter 7, LINQ Performance
    8. Chapter 8, File and Stream I/O
    9. Chapter 9, Enhancing the Performance of Networked Applications
    10. Chapter 10, Setting Up Our Database Project
    11. Chapter 11, Benchmarking Relational Data Access Frameworks
    12. Chapter 12, Responsive User Interfaces
    13. Chapter 13, Distributed Systems
    14. Chapter 14, Multi-Threaded Programming
    15. Chapter 15, Parallel Programming
    16. Chapter 16, Asynchronous Programming
    17. Why subscribe?
  26. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share Your Thoughts

Product information

  • Title: High-Performance Programming in C# and .NET
  • Author(s): Jason Alls
  • Release date: July 2022
  • Publisher(s): Packt Publishing
  • ISBN: 9781800564718