Clean Code in C#
eBook - ePub

Clean Code in C#

Refactor your legacy C# code base and improve application performance by applying best practices

Jason Alls

Compartir libro
  1. 500 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Clean Code in C#

Refactor your legacy C# code base and improve application performance by applying best practices

Jason Alls

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Develop your programming skills by exploring essential topics such as code reviews, implementing TDD and BDD, and designing APIs to overcome code inefficiency, redundancy, and other problems arising from bad code

Key Features

  • Write code that cleanly integrates with other systems while maintaining well-defined software boundaries
  • Understand how coding principles and standards enhance software quality
  • Learn how to avoid common errors while implementing concurrency or threading

Book Description

Traditionally associated with developing Windows desktop applications and games, C# is now used in a wide variety of domains, such as web and cloud apps, and has become increasingly popular for mobile development. Despite its extensive coding features, professionals experience problems related to efficiency, scalability, and maintainability because of bad code. Clean Code in C# will help you identify these problems and solve them using coding best practices.

The book starts with a comparison of good and bad code, helping you understand the importance of coding standards, principles, and methodologies. You'll then get to grips with code reviews and their role in improving your code while ensuring that you adhere to industry-recognized coding standards. This C# book covers unit testing, delves into test-driven development, and addresses cross-cutting concerns. You'll explore good programming practices for objects, data structures, exception handling, and other aspects of writing C# computer programs. Once you've studied API design and discovered tools for improving code quality, you'll look at examples of bad code and understand which coding practices you should avoid.

By the end of this clean code book, you'll have the developed skills you need in order to apply industry-approved coding practices to write clean, readable, extendable, and maintainable C# code.

What you will learn

  • Write code that allows software to be modified and adapted over time
  • Implement the fail-pass-refactor methodology using a sample C# console application
  • Address cross-cutting concerns with the help of software design patterns
  • Write custom C# exceptions that provide meaningful information
  • Identify poor quality C# code that needs to be refactored
  • Secure APIs with API keys and protect data using Azure Key Vault
  • Improve your code's performance by using tools for profiling and refactoring

Who this book is for

This coding book is for C# developers, team leads, senior software engineers, and software architects who want to improve the efficiency of their legacy systems. A strong understanding of C# programming is required.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Clean Code in C# un PDF/ePUB en línea?
Sí, puedes acceder a Clean Code in C# de Jason Alls en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C#. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2020
ISBN
9781838985691
Edición
1
Threading and Concurrency
A process is essentially a program that is executing on an operating system. This process is made up of more than one thread of execution. A thread of execution is a set of commands issued by a process. The ability to execute more than one thread at a time is known as multi-threading. In this chapter, we are going to look at multi-threading and concurrency.
Multiple threads are allotted a set amount of time to execute, and each thread is executed on a rotational basis by a thread scheduler. The thread scheduler schedules the threads using a technique called time slicing and then passes each thread to the CPU to be executed at the scheduled time.
Concurrency is the ability to run more than one thread at exactly the same time. This can be accomplished on computers with more than one processor core. The more processor cores a computer has, the more threads of execution can be executed concurrently.
As we look at concurrency and threading in this chapter, we will encounter the problems of blocking, deadlocks, and race conditions. You will see how we can overcome these problems using clean coding techniques.
In the course of this chapter, we will cover each of the following topics:
  • Understanding the thread life cycle
  • Adding thread parameters
  • Using a thread pool
  • Using a mutual exclusion object with synchronous threads
  • Working with parallel threads using semaphores
  • Limiting the number of processors and threads in the thread pool
  • Preventing deadlocks
  • Preventing race conditions
  • Understanding static constructors and methods
  • Mutability, immutability, and thread safety
  • Synchronized method dependencies
  • Using the Interlocked class for simple state changes
  • General recommendations
After working through this chapter and developing your threading and concurrency skills, you will have acquired the following skills:
  • The ability to understand and discuss the thread life cycle
  • An understanding of and ability to use foreground and background threads
  • The ability to throttle threads and set the number of processors to use concurrently using a thread pool
  • The ability to understand the effects of static constructors and methods in relation to multi-threading and concurrency
  • The ability to take into account mutability and immutability and their impact on thread safety
  • The ability to understand what causes race conditions and how to avoid them
  • The ability to understand what causes deadlocks and how to avoid them
  • The ability to perform simple state changes using the Interlocked class
To run through the code in this chapter, you will need a .NET Framework console application. Unless otherwise stated, all code will be placed in the Program class.

Understanding the thread life cycle

Threads in C# have an associated life cycle. The life cycle for threads is as follows:
When a thread starts, it enters the running state. When running, the thread can enter a wait, sleep, join, stop, or suspended state. Threads can also be aborted. Aborted threads enter the stop state. You can suspend and resume a thread by calling the Suspend() and Resume() methods, respectively.
A thread will enter the wait state when the Monitor.Wait(object obj) method is called. The thread will then continue when the Monitor.Pulse(object obj) method is called. Threads enter sleep mode by calling the Thread.Sleep(int millisecondsTimeout) method. Once the elapsed time has passed, the thread returns to the running state.
The Thread.Join() method causes a thread to enter the wait state. A joined thread will remain in the wait state until all dependent threads have finished running, upon which it will enter the running state. However, if any dependent threads are aborted, then this thread is also aborted and enters the stop state.
Threads that have completed or have been aborted cannot be restarted.
Threads can run in the foreground or the background. Let's look at both foreground and background threads, starting with foreground threads:
  • Foreground threads: By default, threads run in the foreground. A process will continue to run while at least one foreground thread is currently running. Even if Main() completes but a foreground thread is running, the application process will remain active until the foreground thread terminates. Creating a foreground thread is really simple, as the following code shows:
var foregroundThread = new Thread(SomeMethodName);
foregroundThread.Start();
  • Background threads: You create a background thread in the same way that you create foreground threads, except that you also have to explicitly set a thread to run in the background, as shown:
var backgroundThread = new Thread(SomeMethodName);
backgroundThread.IsBackground = true;
backgroundThread.Start();
Background threads are used to carry out background tasks and keep the user interface responsive to the user. When the main process terminates, any background threads that are executing are also terminated. However, even if the main process terminates, any foreground threads that are running will run to completion.
In the next section, we will look at thread parameters.

Adding thread parameters

Methods that run in threads often have parameters. So, when executing a method within a thread, it is useful to know how to pass the method parameters into the thread.
Let's say that we have the following method, which adds two integers together and returns a result:
private static int Add(int a, int b)
{
return a + b;
}
As you can see, the method is simple. There are two parameters called a and b. These two parameters will need to be passed into the thread for the Add() method to run properly. We will add an example method that will do just that:
private static void ThreadParametersExample()
{
int result = 0;
Thread thread = new Thread(() => { result = Add(1, 2); });
thread.Start();
thread.Join();
Message($"The addition of 1 plus 2 is {result}.");
}
In this method, we declare an integer with an initial value of 0. We then create a new thread that calls the Add() method with the 1 and 2parameter values, and then assign the result to the integer variable. The thread then starts and we wait for it to finish executing by calling theJoin()method. Finally, we print the result to the console window.
Let's add ourMessage()method:
internal static void Message(string message)
{
Console.WriteLine(message);
}
The Message() method simply takes a string and outputs it to the console window. All we have to do now is update the Main() method, as follows:
static void Main(string[] args)
{
ThreadParametersExample();
Message("=== Press any Key to exit ===");
Console.ReadKey();
}
In our Main() method, we call our example method and then wait for the user to press any key before exiting. You should see the following output:
As you can see, 1 and 2 were the method parameters passed into the addition method, and 3 was the value returned by the thread. The next topic we will look at is using a thread pool.

Using a thread pool

A thread pool improves performance by creating a collection of threads during application initialization. When a thread is required, it is assigned a single task. That task will be executed. Once executed, the thread is returned to the thread pool to be reused.
Since thread creation is expensive in .NET, we can improve performance by using a thread pool. Each process has a fixed number of threads based on the system resourcesavailable, such as memory and the CPU. However, we can increase or decrease the number of threads used by the thread pool. It is normally best to let the thread pool take care of how many threads to use, rather than manually setting these values.
The different ways to create a thread pool are as follows:
  • Using the Task Parallel Library (TPL) (on .NET Framework 4.0 and higher)
  • Using ThreadPool.QueueUserWorkItem()
  • Using asynchronous delegates
  • Using BackgroundWorker
As a rule of thumb, you should only use a thread pool for server-s...

Índice