High-Performance Programming in C# and .NET - Jason Alls - E-Book

High-Performance Programming in C# and .NET E-Book

Jason Alls

0,0
37,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 645

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



High-Performance Programming in C# and .NET

Understand the nuts and bolts of developing robust, faster, and resilient applications in C# 10.0 and .NET 6

Jason Alls

BIRMINGHAM—MUMBAI

High-Performance Programming in C# and .NET

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Associate Group Product Manager: Gebin George

Publishing Product Manager: Alok Dhuri

Senior Editor: Kinnari Chohan

Technical Editor: Maran Fernandes

Copy Editor: Safis Editing

Project Coordinator: Manisha Singh

Proofreader: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Sinhayna Bais

Marketing Coordinator: Sonakshi Bubbar

First published: July 2022

Production reference: 1290722

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80056-471-8

www.packt.com

I would like to dedicate this book to the team at Packt, who helped me through each step of the way and were very accommodating and understanding of the difficulties I was going through in my personal life while working on this book. They have been a truly great team that has encouraged me each step of the way. I could not have written this book without their expertise and guidance.

I would also like to dedicate this book to my wonderful parents, who had to suffer long periods without me as I spent many a long night and many weekends on this book, but who encouraged me to keep going through difficult times.

– Jason Alls

Contributors

About the author

Jason Alls is the author of Clean Code in C# and has been programming for over 21 years. Working with an Australasian company, he started his career developing call center management reporting software used by global clients, including telecom providers, banks, airlines, and the police. He then moved on to develop GIS marketing applications and worked in the banking sector, performing data migrations between Oracle and SQL Server. Certified as an MCAD in C# since 2005, he has been involved in the development of various desktop, web, and mobile applications.

Currently employed by a leading software house, he develops and supports order processing and warehouse management software written in C#.

I would like to send a warm thank you to Joy and Gianni, who reviewed the chapters for me. Their attention to detail was excellent, and they would often let me know when things needed improving or when I had left something out. Because of them, the content of this book, I feel, will be of great benefit to programmers and developers at all levels. I happily recommend them as reviewers to any budding authors.

About the reviewers

Gianni Rosa Gallina is an Italian senior software engineer and architect who has been focused on emerging technologies, AI, and virtual/augmented reality since 2013. Currently, he works at Deltatre’s Innovation Lab, prototyping solutions for next-generation sports experiences and business services. Besides that, he has more than 10 years of certified experience as a consultant on Microsoft and .NET technologies (including technologies such as the Internet of Things, the cloud, and desktop/mobile apps). Since 2011, he has been awarded Microsoft MVP in the Windows Development category. He has been a Pluralsight Author since 2013 and is a speaker at national and international conferences.

Joy Rathnayake is a solutions architect with over 19 years of industry experience and is part of the Digital & Emerging Technology (DET) team at EY GDS, based in Colombo, Sri Lanka. He is primarily responsible for understanding customer requirements, identifying required products/ technologies, and defining the overall solution design/ architecture.

Before he joined EY GDS Sri Lanka, Joy worked as a solutions architect at WSO2 Inc., Totalamber Ltd, Virtusa Ltd, Solid Quality Mentors, IronOne Technologies, and Sri Lankan Airlines. He was responsible for architecting, designing, and developing software solutions primarily using Microsoft and related technologies.

Joy has been recognized as both a Microsoft Most Valuable Professional (MVP) and a Microsoft Certified Trainer (MCT). He has contributed to developing content for Microsoft Certifications and has worked as a Subject Matter Expert (SME) for many Microsoft exam development projects.

He has contributed a lot to the community by presenting at various events, such as Microsoft Tech-Ed, Southeast Asia SharePoint Conference, and SharePoint Saturday.

Joy enjoys traveling, speaking at public events/conferences, and reading.

Table of Contents

Preface

Part 1: High-Performance Code Foundation

Chapter 1: Introducing C# 10.0 and .NET 6

Technical requirements

Obtaining and building the latest Roslyn compiler from the source code

Overview of Microsoft .NET 6

Moving to one unified platform

Garbage collection

Just-In-Time compiler

Text-based processing

Threading and asynchronous operations

Collections and LINQ

Networking and Blazor

New performance-based APIs and analyzers

Overview of C# 10.0

Writing top-level programs

Using init-only properties

Using records

Using the new pattern matching features

Using new expressions with targeted types

Using covariant returns

Native compilation

Performing native compilation of .NET Core applications

Improving Windows Store performance

Improving ASP.NET performance

Summary

Questions and exercises

Further reading

Chapter 2: Implementing C# Interoperability

Technical requirements

Using Platform Invocation (P/Invoke)

Using unsafe and fixed code

Exposing static entry points using P/Invoke

Interacting with Python code

Performing Component Object Model (COM) interoperability

Reading data from an Excel spreadsheet

Creating an Excel add-in

Safely disposing of unmanaged code

Summary

Questions

Further reading

Chapter 3: Predefined Data Types and Memory Allocations

Technical requirements

Understanding the predefined .NET data types

Understanding the predefined value types in C#

Understanding the predefined reference types in C#

Understanding static types

Understanding the various types of memory used in C#

The stack

The heap

Building a stack versus building a heap (example project)

Choosing between a struct and a class

Passing by value and passing by reference

Building a pass-by-reference example program

Boxing and unboxing

Performing boxing

Performing unboxing

Summary

Questions

Further reading

Chapter 4: Memory Management

Technical requirements

Object generations and avoiding memory issues

Understanding long and short weak references

Finalization

Using finalization

Implementing the IDisposable pattern

Preventing memory leaks

Understanding the dangers of using Marshal.ReleaseComObject

How using events can be a source of memory leaks

Summary

Questions

Further reading

Chapter 5: Application Profiling and Tracing

Technical requirements

Understanding code metrics

Application metrics

Assembly metrics

Namespace metrics

Type metrics

Method metrics

Field metrics

Performing static code analysis

Generating and viewing memory dumps

Viewing loaded modules

Debugging your applications

Using tracing and diagnostics tools

Using the Visual Studio 2022 Performance Profiler

Using JetBrains dotMemory

Using JetBrains dotTrace

Installing and using dotnet-counters

Collecting data and saving it to a file for post-analysis

Listing .NET processes that can be monitored

Listing the available list of well-known .NET counters

Monitoring a .NET process

Tracking down and fixing a memory leak with dotMemory

Finding the cause of a UI freeze with dotTrace

Optimizing application performance and memory traffic with dotTrace

Summary

Questions

Further reading

Part 2: Writing High-Performance Code

Chapter 6: The .NET Collections

Technical requirements

Understanding the different collection offerings

The System.Collections namespace

The System.Collections.Generic namespace

The System.Collections.Concurrent namespace

The System.Collections.Specialized namespace

Creating custom collections

Understanding Big O notation

Choosing the right collection

Setting up our sample database

Deciding between interfaces and concrete classes

Deciding between using arrays or collections

Accessing objects using indexers

Comparing IEnumerable and IEnumerator

Database query performance

Exploring the yield keyword

Learning the difference between concurrency and parallelism

Summary

Questions

Further reading

Chapter 7: LINQ Performance

Technical requirements

Setting up a sample database

Setting up our in-memory sample data

Database query performance

Getting the last value of a collection

Avoid using the let keyword in LINQ queries

Increasing Group By performance in LINQ queries

Filtering lists

Understanding closures

Summary

Questions

Further reading

Chapter 8: File and Stream I/O

Technical requirements

Understanding the various Windows file path formats

Removing the maximum path length limitation using the registry

Removing the maximum path length limitation using the group policy

Considering improved I/O performance

Moving files

Calculating directory sizes

Accessing files asynchronously

Writing text to a file asynchronously

Handling I/O operation exceptions

Performing memory tasks efficiently

Understanding local storage tasks

Summary

Questions

Further reading

Chapter 9: Enhancing the Performance of Networked Applications

Technical requirements

Understanding the network layers and protocols

The TCP/IP model

Writing an example email application with the TCP/IP model

Improving web-based network traffic

Recording your web-applications performance using Microsoft Edge

High-performance communication using gRPC

Programming a simple gRPC client/server application

Programming a simple gRPC Blazor application

The blank solution

Optimizing internet resources

Using pipelines for content streaming

Writing and running a TCP server console application

Writing and running a TCP client console application

Caching resources in memory

Summary

Questions

Further reading

Chapter 10: Setting Up Our Database Project

Technical requirements

Setting up our database

Setting up our database access project

Writing the Properties class

Writing the DatabaseSettings class

Writing the SecretsManager

Writing the Product class

Writing the SqlCommandModel class

Writing the SqlCommandParameterModel class

Writing the AdoDotNet class

Writing the EntityFrameworkCoreData class

Writing the DapperDotNet class

Summary

Further reading

Chapter 11: Benchmarking Relational Data Access Frameworks

Technical requirements

Benchmarking data insertion methods

Benchmarking data selection methods

Benchmarking data editing methods

Benchmarking data deletion methods

The benchmarking results and their analysis

Summary

Questions

Further reading

Chapter 12: Responsive User Interfaces

Technical requirements

Building a responsive UI with WinForms

Enabling DPI awareness and long file path awareness

Adding a splash screen that updates with loading progress

Adding the increment count button and label

Adding a table with paged data

Running long-running tasks in the background

Building a responsive UI with WPF

Building a responsive UI with ASP.NET

Implementing memory caching

Implementing distributed caching

Using AJAX to update part of the currently displayed page

Implementing WebSockets

Implementing a real-time chat application using SignalR

Building responsive UIs with .NET MAUI

Layouts

Accessibility

BlazorWebView

Building a responsive UI with MAUI

Building a responsive UI with WinUI 3

Summary

Questions

Further reading

Chapter 13: Distributed Systems

Technical requirements

Implementing the CQRS design pattern

Implementing event sourcing

Event sourcing example project

Using Microsoft Azure for distributed systems

Azure Functions

Durable Azure Functions

Containers and serverless

Managing your cloud infrastructure with Pulumi

Performance considerations for distributed computing

Summary

Questions

Further reading

Part 3: Threading and Concurrency

Chapter 14: Multi-Threaded Programming

Technical requirements

Understanding threads and threading

Creating threads and using parameters

Pausing and interrupting threads

Destroying and canceling threads

Scheduling threads

Thread synchronization and locking

Summary

Questions

Further reading

Chapter 15: Parallel Programming

Technical requirements

Using the Task Parallel Library (TPL)

Using Parallel LINQ (PLINQ)

Programming parallel data structures

Benchmarking with BenchmarkDotNet

Using lambda expressions with TPL and LINQ

Parallel debugging and profiling tools

The Parallel Stacks window

The Tasks window

The Concurrency Visualizer

Summary

Questions

Further reading

Chapter 16: Asynchronous Programming

Technical requirements

Understanding the TAP model

Naming, parameters, and return types

Initiating asynchronous operations

Exceptions

Optional cancellation

Optional Progress Reporting

async, await, and Task

Benchmarking GetAwaiter.GetResult(), .Result, and .Wait for both Task and ValueTask

Using async, await, and WhenAll

Canceling asynchronous operations

Writing files asynchronously

Reading files asynchronously

Summary

Questions

Further reading

Assessments

Chapter 1, Introducing C# 10.0 and .NET 6

Chapter 2, Implementing C# Interoperability

Chapter 3, Predefined Data Types and Memory Allocations

Chapter 4, Memory Management

Chapter 5, Application Profiling and Tracing

Chapter 6, The .NET Collections

Chapter 7, LINQ Performance

Chapter 8, File and Stream I/O

Chapter 9, Enhancing the Performance of Networked Applications

Chapter 10, Setting Up Our Database Project

Chapter 11, Benchmarking Relational Data Access Frameworks

Chapter 12, Responsive User Interfaces

Chapter 13, Distributed Systems

Chapter 14, Multi-Threaded Programming

Chapter 15, Parallel Programming

Chapter 16, Asynchronous Programming

Other Books You May Enjoy

Part 1: High-Performance Code Foundation

Part 1 covers the foundation of high-performance code. We cover what’s new in C# 10.0 and .NET 6, including performance improvements. Next, we look at the interoperability that is available that allows the gradual porting of Python systems to C#, followed by the garbage collector. You will learn how types can negatively impact performance, as can manually calling the garbage collector. And finally, we look at how we can use profiling tools to identify and address performance issues.

This part contains the following chapters:

Chapter 1, Implementing C# 10.0 and .NET 6Chapter 2, Introducing C# InteroperabilityChapter 3, Predefined Data Types and Memory AllocationsChapter 4, Memory ManagementChapter 5, Application Profiling and Tracing