воскресенье, 14 февраля 2010 г.

Что нового в третьем издании книги Джеффри Рихтера “CLR via C#”

CLR

До официального выхода третьего издания знаменитой книги Джеффри Рихтера “CLR via C#” остался еще один день (официальная дата выхода – 15 февраля 2010 года), а доброжелатели уже постарались над тем, чтобы эта книга стала достоянием широкой общественности.

Но речь здесь пойдет не об этом, а о тех нововведениях, которые появились в третьем издании по сравнению со вторым (хотя содержание третьего издания уже давно доступно, но сравнивать вручную содержания двух книг – дело хлопотное, поверьте, я только что этим занимался:)). Кроме того, некоторые темы я пробежался глазами, чтобы определить в чем именно заключаются отличия.

Первое, что бросается в глаза, так это то, что третье издание "подросло" в объеме чуть более чем на 150 страниц. Второе издание содержит 736 страниц, а третье - 896.

Первое изменение в содержании (не путать с содержимым, хотя есть сомнения в изменении содержимого первых четырех глав) найдена только лишь главе 5. Primitive, Reference, and Value Types): в третьем издании появился раздел: The dynamic Primitive type.

Глава 8 второго издания: Methods: Constructors, Operators, Conversions, and Parameters... разбита на две главы в третьем: Глава 8. Methods, Глава 9. Parameters.

Глава 8. Methods. В третьем издании добавлены нововведения из C#3.0:
Extension Methods
   Rules and Guidelines
   Extending Various Types with Extension Methods
   The Extension Attribute
Partial Methods
   Rules and Guidelines

Главе 9. Parameters. В третьем издании добавлены нововведения C# 3.0 и 4.0:
Optional and Named Parameters
   Rules and Guidelines
   The DefaultParameterValue and Optional Attributes
Implicitly Typed Local Variables
Parameter and Return Type Guidelines

Главе 10. Properties. В третьем издании добавлены нововведения C# 3.0 и C#4.0 :
Parameterless Properties
   Automatically Implemented Properties
   Object and Collection Initializers
   Anonymous Types
   The System.Tuple Type

Глава по обобщениям (Generics) теперь стала 12-й (во втором издании, была 16-й). Содержание этих глав совпадает, но размер этой главы в третьем издании увеличился с 28 страниц до 32. Буду рад, если кто-то скажет об отличиях:)

Глава 15. Enumerated Types and Bit Flags. В третьем издании добавлен раздел Adding Methods to Enumerated Types, в котором рассказывается о добавлении методов перечислениям с помощью методов расширения.

Глава 16. Arrays. В третьем издании добавлен раздел Initializing Array Elements, в котором говорится о новых возможностях инициализации массивов, появившихся в C# 3.0

Глава 17. Delegates. В третьем издании раздел Syntactical Shortcut #2: No Need to Define a Callback Method переписан с применением лямбда-выражений.

Глава 20. Exceptions and State Management. Теперь глава об обработке исключений называется именно так. В ней многие разделы имеют немного другие названия и слегка перетасованы (сложно сказать, как это отразилось на содержимом), но появились два новых раздела: Constrained Execution Regions (CERs) и Code Contracts

Глава 21. Automatic Memory Management (Garbage Collection). Содержание глав во втором и третьем издании практически совпадают, единственное отличие состоит в том, что в третьем издании эта глава на 8 страниц длиннее (72 в третьем издании, 64 - во втором).

Глава 22. CLR Hosting and AppDomains. Появились следующие разделы: AppDomain Monitoring, AppDomain First-Chance Exception Notifications, отличается раздел How Hosts Use AppDomains.

Глава 24. Runtime Serialization. Это новая глава, которая появилась в только в третьем издании книги.
Serialization/Deserialization Quick Start
Making a Type Serializable
Controlling Serialization and Deserialization
How Formatters Serialize Type Instances
Controlling the Serialized/Deserialized Data
   How to Define a Type That Implements ISerializable when the Base Type Doesn’t Implement This Interface
Streaming Contexts
Serializing a Type as a Different Type and Deserializing an Object as a Different Object
Serialization Surrogates
   Surrogate Selector Chains
Overriding the Assembly and/or Type When Deserializing an Object

Часть 5 теперь называется Threading. Наконец-то Рихтер оказался в своей стихии. В третьем издании вопросам многопоточности уделено 180 (!) страниц, а во втором издании только 64(!). Т.е. эту часть можно читать целиком.

Глава 25. Thread Basics
Why Does Windows Support Threads?
Thread Overhead
Stop the Madness
CPU Trends
NUMA Architecture Machines
CLR Threads and Windows Threads
Using a Dedicated Thread to Perform an Asynchronous Compute-Bound Operation
Reasons to Use Threads
Thread Scheduling and Priorities
Foreground Threads versus Background Threads
What Now?

Глава 26 Compute-Bound Asynchronous Operations
Introducing the CLR’s Thread Pool
Performing a Simple Compute-Bound Operation
Execution Contexts
Cooperative Cancellation
Tasks
   Waiting for a Task to Complete and Getting Its Result
   Cancelling a Task
   Starting a New Task Automatically When Another Task Completes
   A Task May Start Child Tasks
   Inside a Task
   Task Factories
   Task Schedulers
Parallel’s Static For, ForEach, and Invoke Methods
Parallel Language Integrated Query
Performing a Periodic Compute-Bound Operation
   So Many Timers, So Little Time
How the Thread Pool Manages Its Threads
   Setting Thread Pool Limits
   How Worker Threads Are Managed
Cache Lines and False Sharing

Глава 27. I/O-Bound Asynchronous Operations
How Windows Performs I/O Operations
The CLR’s Asynchronous Programming Model (APM)
The AsyncEnumerator Class
The APM and Exceptions
Applications and Their Threading Models
Implementing a Server Asynchronously
The APM and Compute-Bound Operations
APM Considerations
   Using the APM Without the Thread Pool
   Always Call the EndXxx Method, and Call It Only Once
   Always Use the Same Object When Calling the EndXxx Method
   Using ref, out, and params Arguments with BeginXxx and EndXxx Methods
   You Can’t Cancel an Asynchronous I/O-Bound Operation
   Memory Consumption
   Some I/O Operations Must Be Done Synchronously
   FileStream-Specific Issues
I/O Request Priorities
Converting the IAsyncResult APM to a Task
The Event-Based Asynchronous Pattern
   Converting the EAP to a Task
   Comparing the APM and the EAP
Programming Model Soup

Глава 28. Primitive Thread Synchronization Constructs
Class Libraries and Thread Safety
Primitive User-Mode and Kernel-Mode Constructs
User-Mode Constructs
   Volatile Constructs
   Interlocked Constructs
   Implementing a Simple Spin Lock
   The Interlocked Anything Pattern
Kernel-Mode Constructs
   Event Constructs
   Semaphore Constructs
   Mutex Constructs
   Calling a Method When a Single Kernel Construct Becomes Available

Глава 29 Hybrid Thread Synchronization Constructs
A Simple Hybrid Lock
Spinning, Thread Ownership, and Recursion
A Potpourri of Hybrid Constructs
   The ManualResetEventSlim and SemaphoreSlim Classes
   The Monitor Class and Sync Blocks
   The ReaderWriterLockSlim Class
   The OneManyLock Class
   The CountdownEvent Class
   The Barrier Class
Thread Synchronization Construct Summary
The Famous Double-Check Locking Technique
The Condition Variable Pattern
Using Collections to Avoid Holding a Lock for a Long Time
The Concurrent Collection Classes

Более подробное мое мнение по поводу содержимого этих изменений, я надеюсь можно будет узнать в ближайшем будущем, когда я с этими самыми изменениями познакомлюсь. Но в одном можно быть уверенным, Рихтер знает свое дело, поэтому если у вас возникнет вопрос о хорошей книге по платформе .NET, первой в этом списке должна быть именно эта книга!

UPDATE:

Только сейчас заметил, что "все уже украдено до нас" и Джеффри Рихтер в своем блоге уже писал об изменениях между вторым и третьим изданиями (почитать об этом можно здесь).

Ко всему, что я написал выше стоит добавить следующее:

Chapter 1-The CLR’s Execution Model
Added about discussion about C#’s /optimize and /debug switches and how they relate to each other.

Chapter 2-Building, Packaging, Deploying, and Administering Applications and Types
Improved discussion about Win32 manifest information and version resource information.

Chapter 3-Shared Assemblies and Strongly Named Assemblies
Added discussion of TypeForwardedToAttribute and TypeForwardedFromAttribute.

Chapter 5-Primitive, Reference, and Value Types
Enhanced discussion of checked and unchecked code and added discussion of new BigInteger type

Chapter 19-Nullable Value Types
Added discussion on performance.

Chapter 20-Exception Handling and State Management
This chapter has been completely rewritten. It is now about exception handling and state management.

Chapter 21-Automatic Memory Management
Added discussion of C#’s fixed state and how it works to pin objects in the heap. Rewrote the code for weak delegates so you can use them with any class that exposes an event (the class doesn’t have to support weak delegates itself). Added discussion on the new ConditionalWeakTable class, GC Collection modes, Full GC notifications, garbage collection modes and latency modes. I also include a new sample showing how your application can receive notifications whenever Generation 0 or 2 collections occur.

Chapter 23-Assembly Loading and Reflection
Added section on how to deploy a single file with dependent assemblies embedded inside it. Added section comparing reflection invoke vs bind/invoke vs bind/create delegate/invoke vs C#’s dynamic type.

Часть 5. Threading таки является полностью новой.

3 комментария:

  1. На родной наш язык быстро переведут?

    ОтветитьУдалить
  2. Надеюсь что быстро, ведь там не так много нового.
    Но практика показывает, что раньше чем через 6-9 месяцев русскоязычный вариант ждать вряд ли стоит.

    ОтветитьУдалить
  3. Уважаемые коллеги.

    На данный момент я не нашел никаких данных о том, что какое-либо издательство занялось переводом этой книги на русский язык. Возможно издатели сомневаются в необходимости этого (хотя это достаточно смешно).

    Для того, чтобы им (издателям) была понятна необходимость этого и чтобы перевод был сделан как можно раньше я создал голосование на rsdn.ru (http://rsdn.ru/poll/2545.aspx), ветку обсуждения на сайте издательства Символ-Плюс (http://www.symbol.ru/forum/viewtopic.php?f=4&t=315).

    Большая просьба по возможности проголосовать, а также оставить сообщения вида +1 на форуме либо здесь в виде комментария.

    ОтветитьУдалить