No description
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
# C并发编程经典实例 (图灵程序设计丛书)
## 【One-Line Pitch】
A practical recipe book for C# developers who want to master modern concurrency — from async/await basics to parallel processing, reactive programming, and dataflow grids — without drowning in low-level thread details. If you write C# applications that need to stay responsive, scale under load, or handle event streams, this book gives you battle-tested patterns for every scenario.
## 【Book Arc】
- **Opening (~0%–12%)**: Debunks common concurrency myths (concurrency ≠ multithreading), introduces the core vocabulary (concurrent, parallel, async, multithreaded), and sets the tone: modern C#/.NET provides high-level abstractions that make concurrency accessible to every developer. The author explicitly avoids legacy `Thread` and `BackgroundWorker` types.
- **Early (~12%–29%)**: Covers async/await fundamentals — creating tasks, returning completed tasks with `Task.FromResult`, waiting for groups with `Task.WhenAll`, avoiding context continuations with `ConfigureAwait(false)`, and handling `async void` exceptions. Then shifts to parallel processing: `Parallel.ForEach`, `Parallel.Invoke`, and PLINQ for data-parallel workloads.
- **Middle (~29%–47%)**: Introduces TPL Dataflow for building dataflow grids and pipelines, then moves into Reactive Extensions (Rx) for event-stream programming — creating observable sequences from events, throttling/sampling fast event streams, and using schedulers for UI-thread marshaling. Includes unit testing strategies for async methods and dataflow grids.
- **Middle (~47%–59%)**: Bridges old and new async patterns by wrapping legacy APM/EAP/callback-based code with `TaskCompletionSource<T>`, and shows how to integrate Rx observables with async/await and dataflow blocks. Covers concurrent collections (blocking queues, async queues) and immutable collections for thread-safe data sharing.
- **Late (~59%–end)**: Covers cancellation (polling, timeouts, injecting cancellation tokens), functional OOP patterns for async interfaces/constructors/properties/events, synchronization primitives (blocking and async locks, signals, throttling), and scheduling to thread pools with custom task schedulers.
## 【Key Takeaways】
- **Concurrency is broader than multithreading** (Early): Modern C# offers async programming, parallel processing, TPL Dataflow, and reactive programming — each suited to different problems. The book's guiding principle: if you find yourself typing `new Thread()`, your code is outdated.
- **`async`/`await` is the foundation for I/O-bound operations** (Early): Use `Task.Run` only for CPU-bound work; for HTTP requests, database calls, and web services, async/await keeps your UI responsive and your server scalable. `ConfigureAwait(false)` in library code avoids UI-context performance degradation.
- **Parallel processing requires independent tasks** (Early): `Parallel.ForEach`, `Parallel.Invoke`, and PLINQ all work best when task blocks are independent. Shared state forces synchronization, which destroys parallelism — design for independence first.
- **Dataflow grids enable complex pipelines** (Middle): TPL Dataflow blocks (BufferBlock, TransformBlock, ActionBlock) can be linked into pipelines with completion propagation and error handling. Use `Encapsulate` to package reusable grid logic into custom blocks.
- **Rx turns events into queryable streams** (Middle): `Observable.FromEventPattern` wraps .NET events into `IObservable<T>` sequences, and operators like `Throttle`, `Sample`, and `Timeout` tame high-frequency event streams. `ObserveOn` marshals notifications to UI threads.
- **`TaskCompletionSource<T>` bridges legacy async patterns** (Middle): APM, EAP, and callback-based code can all be wrapped into awaitable `Task<T>` objects, making old code compatible with modern async/await.
- **Choose collections by access pattern** (Middle): `ConcurrentDictionary<TKey,TValue>` excels for shared mutable state; immutable collections (`ImmutableList<T>`, `ImmutableDictionary<TKey,TValue>`) are better for rarely-modified, multi-threaded reads — but watch the O(log N) indexing cost of `ImmutableList<T>`.
- **Cancellation should be cooperative and pervasive** (Late): Use `CancellationTokenSource` with polling, timeouts, and injection patterns. Async, parallel, and reactive code all support cancellation — but you must design for it from the start.
## 【Reading Tips】
- **Skim Chapter 1** if you're already familiar with async/await basics — the myth-busting is motivational, but the real value starts with Chapter 2's async recipes.
- **Deep-read Chapters 2–3** for the core async/parallel patterns; these are the foundation for everything else. Pay special attention to `ConfigureAwait(false)` and the difference between stopping and cancelling parallel loops.
- **Chapters 4–5 (Dataflow and Rx) are the most conceptually dense** — read them together, as the book frequently cross-references them. The Rx event-stream examples (throttling mouse moves, wrapping timers) are worth working through slowly.
- **Chapter 7 is a practical goldmine** for anyone maintaining legacy code — the `TaskCompletionSource<T>` wrapping patterns are directly applicable to real-world migration scenarios.
- **Use the "参阅" (see also) cross-references** as a navigation tool; the book is structured as independent recipes, so you can jump directly to the pattern you need.
## 【Coverage Limits】
This guide covers the book's progression through async/await, parallel processing, dataflow, reactive programming, collections, and cancellation. The excerpts do not cover the final chapters on synchronization primitives (Chapter 11) and scheduling (Chapter 12) in detail, nor the functional OOP patterns (Chapter 10) beyond their table-of-contents listing.
##
Excerpt 1
代码中,只在需要时才恢复上 下⽂。 关键字await不仅能⽤于任务,还能⽤于所有遵循特定模式的 awaitable类型。例如,Windows Runtime API定义了⾃⼰专⽤的异步操 作接⼝。这些接⼝不能转化为Task类型,但确实遵循了可等待的 (awaitable)模式,因此可以直接使⽤await。这种aw...
View in text
Excerpt 2
,但建 议⼤家不要使⽤。只要异步代码与LINQ结合,显式的“具体化”序列 (即对序列求值,创建集合)就会使代码更清晰: static async Task<string> DownloadAllAsync(IEnumerable<string> urls) { var httpClient = new HttpC...
View in text
Excerpt 3
sed"); ticks.Subscribe(data => Trace.WriteLine("OnNext: " + ((ElapsedEventArgs)data.EventArgs).SignalTime)); 采⽤这种⽅法后,调⽤FromEventPattern就简单多了。但是这种 ⽅法也有缺点:出现了⼀...
View in text
Excerpt 4
到了测试问题。实际上,Rx库本⾝就已经过⼤量 单元测试。为了解决上⾯的问题,Rx引⼊了调度器(scheduler)这⼀ 概念,每个与时间有关的Rx操作都在实现时使⽤了这个抽象的调度 器。 要让observable对象便于测试,就要允许调⽤它的程序指定调度器。例 如可以使⽤6.5节的MyTimeoutClass,并...
View in text
Excerpt 5
类提供了TryDequeueAsync 成员,可以⽤来避免冗⻓的消费者代码。如果有多个消费者,消费者 代码通常像这样: while (true) { var dequeueResult = await _asyncQueue.TryDequeueAsync(); if (!dequeueResult.Succes...
View in text
Excerpt 6
通过关闭⼀些资源来实现取消,⽽关闭资 源会取消多个操作。此类取消体系就不⼤适合使⽤ CancellationToken。如果你⼀定要⽤CancellationToken封装 此类取消体系,那就在⽂档中把这个不寻常的语法描述清楚吧。 要特别注意回调函数注册的⽣命周期。Register⽅法返回⼀个可释 放的对象,应该...
View in text
Excerpt 7
_value1 + _value2; } public void Initialize() { _value1 = 13; _value2 = 17; _initialized.TrySetResult(null); } } 在所有情况下都可以⽤TaskCompletionSource<T>来异步地等 待:本例中...
View in text
Excerpt 8
功能只有在代码运⾏时才起作⽤。例 如对⼀个运⾏异步代码的执⾏块启⽤⼀个独占调度器,当它正在等待 时,不被认为是在运⾏。 private static readonly AsyncLazy<int> MySharedAsyncInteger =new AsyncLazy<int>(async () => { awa...
View in text
Tags
AI categories
Programming LanguageBackend
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Generating text preview…
Loading comments...
Reply to Comment
Edit Comment