Latest / CyberSecurity Summary / Concurrency in C# Cookbook: Asynchronous, Parallel, and Multithreaded Programming
Transcript
- 0:00Speaker 1: Welcome to the deep dive. Today, we are getting into
- 0:02Speaker 1: something that, well, if you're a developer, it has probably
- 0:06Speaker 1: kept you up at night at least once. We're talking
- 0:09Speaker 1: about modern concurrency and sea shark.
- 0:11Speaker 2: Yeah, it's it's a massive topic.
- 0:14Speaker 1: It really is. And we are pulling our insights today
- 0:17Speaker 1: from some excerpts of Stephen Cleary's Concurrency and c Shark cookbook.
- 0:21Speaker 1: Our mission here is to really just extract the critical
- 0:24Speaker 1: knowledge you need to master responsive scalable programming, you know,
- 0:29Speaker 1: without getting bogged down by the absolute nightmares of old
- 0:32Speaker 1: school multi threading, right.
- 0:33Speaker 2: Because nobody wants to go back to those nightmares. I
- 0:35Speaker 2: mean it's just it's.
- 0:36Speaker 1: Rough, definitely not. But before we get into the code,
- 0:39Speaker 1: I have to talk about the cover of this book.
- 0:41Speaker 1: If you haven't seen it, you might expect, I don't know,
- 0:44Speaker 1: a majestic animal like maybe a falcon or a cheetah,
- 0:47Speaker 1: something to represent speed and raw power.
- 0:49Speaker 2: Yeah, that would make sense for a book on concurrency.
- 0:51Speaker 1: Right, But instead you get a common palms of bit.
- 0:55Speaker 1: And if you read the author's own preface, he actually
- 0:58Speaker 1: points out that this animal is widely considered like it
- 1:00Speaker 1: gets into attics, it poops everywhere, and it just makes
- 1:03Speaker 1: these incredibly loud, crashing noises at the absolute worst possible times.
- 1:08Speaker 2: And there's another really funny detail about the civet. It
- 1:12Speaker 2: eats coffee cherries and well passes the beans through its
- 1:15Speaker 2: digestive tract, which is just ea yeah, but those excreted
- 1:19Speaker 2: beans are actually harvested to make Kobe Luwac, which is
- 1:22Speaker 2: notoriously one of the most expensive coffees in the world.
- 1:26Speaker 2: Yet and this is the best part. The Specialty Coffee
- 1:29Speaker 2: Association officially states that it quote just tastes bad.
- 1:33Speaker 1: Oh wow. So it's expensive but awful exactly.
- 1:36Speaker 2: And the author chose this mascot for a very specific, deliberate.
- 1:40Speaker 1: Reason because to anyone who has been in the trenches,
- 1:43Speaker 1: to the uninitiated, old school multi threading is exactly like
- 1:46Speaker 1: the civet. I mean, it is a messy pest. It
- 1:48Speaker 1: causes loud, unpredictable crashes. And this crashes usually happen you know,
- 1:52Speaker 1: the value moment you.
- 1:53Speaker 2: Deployed at production yep, always in production.
- 1:55Speaker 1: Always and after all the time, the money, the sleepless
- 1:58Speaker 1: nights you spend trying to fix it, it leaves a
- 2:00Speaker 1: really bad taste in your mouth.
- 2:02Speaker 2: It really does. And I think the mission of our
- 2:04Speaker 2: deep dive today is to show you how modern c
- 2:07Speaker 2: shark has just completely evolved past that mess. We are
- 2:11Speaker 2: moving away from writing strict, step by step instructions that
- 2:14Speaker 2: forcefully micromanage your system resources, and we're moving toward well
- 2:20Speaker 2: choreographing a self balancing digital ecosystem. It is a fundamental
- 2:24Speaker 2: shift in how we architect applications today.
- 2:27Speaker 1: Okay, let's unpack this because the author he really doesn't
- 2:30Speaker 1: pull any punches regarding that shift. There's this brutal, just
- 2:34Speaker 1: instantly memorable quote early in the text. It simply says,
- 2:37Speaker 1: as soon as you type new thread, it's over. Your
- 2:39Speaker 1: project already has legacy code.
- 2:41Speaker 2: Ouch. Yeah, which is I mean, that's a tough pill
- 2:43Speaker 2: to swallow. If you grew up manually spinning up threads.
- 2:46Speaker 1: It feels wrong, It feels like you're losing control right.
- 2:49Speaker 2: Exactly, But it requires us to really look at what
- 2:53Speaker 2: the run time is actually doing. Now we have to
- 2:55Speaker 2: clarify the terminology here. Multi threading is just one form
- 2:59Speaker 2: of concurrency, the direct manual management of threads, you know,
- 3:03Speaker 2: allocating them, destroying them, trying to figure out exactly how
- 3:07Speaker 2: many your specific hardware can handle that is dead.
- 3:10Speaker 1: But the threads of themselves aren't gone obviously.
- 3:12Speaker 2: Right right, They're just abstracted. They live on behind the
- 3:15Speaker 2: thread pool under the hood. And the modern net threadpool
- 3:19Speaker 2: is this highly optimized dynamic heuristic algorithm.
- 3:22Speaker 1: So it's making decisions for you.
- 3:24Speaker 2: Yeah, constantly. It monitors the CPU load, the memory constrains,
- 3:28Speaker 2: the queue of pending work, and it just continuously adjusts
- 3:32Speaker 2: the number of active threads on the fly. I mean,
- 3:34Speaker 2: it is vastly better at managing resource allocation than any
- 3:37Speaker 2: custom code you or I could ever write.
- 3:39Speaker 1: It's kind of like, I mean, think about legacy threading
- 3:41Speaker 1: like manually moving the gears inside your car's transmission by hand,
- 3:44Speaker 1: just constantly grinding them, whereas modern concurrency is like an
- 3:48Speaker 1: automatic transmission that dynamically adjusts to the traffic around you.
- 3:51Speaker 2: That's a really good analogy. Yeah, but just handing over
- 3:54Speaker 2: thread allocation to the run time, you know, that isn't
- 3:57Speaker 2: enough to prevent the classic nightmare scenario.
- 4:00Speaker 1: Like deadlocks and race conditions exactly.
- 4:03Speaker 2: The source material emphasizes that modern concurrency heavily relies on
- 4:07Speaker 2: adopting a functional mindset.
- 4:08Speaker 1: Okay, so what does that actually mean in practice, Well.
- 4:11Speaker 2: It's the real secret sauce. Modern concurrency strongly leans toward
- 4:16Speaker 2: writing pure code. That means methods that take inputs, produce outputs,
- 4:21Speaker 2: and have zero side effects. And you combine that with
- 4:25Speaker 2: immutable data structures.
- 4:27Speaker 1: Meaning data that literally cannot be changed in memory once
- 4:30Speaker 1: it has been created.
- 4:31Speaker 2: Right, So if the data can't change, multiple threads can
- 4:34Speaker 2: read it simultaneously without needing complex locks. You inherently bypass
- 4:39Speaker 2: the synchronization issues entirely because well, there's nothing to synchronize.
- 4:43Speaker 1: Wow, okay, so you eliminate shared state, and when you
- 4:45Speaker 1: eliminate shared mutable state, those classic multi threading bugs just sort.
- 4:49Speaker 2: Of evaporate, they do. They just go away.
- 4:51Speaker 1: So, if we aren't creating threads manually anymore, how do
- 4:55Speaker 1: we handle tasks that take time? Like how do we
- 4:58Speaker 1: wait for external cs stems to respond without locking up
- 5:02Speaker 1: our entire application?
- 5:03Speaker 2: That takes us right into the mechanics of asynchronous programming,
- 5:07Speaker 2: the async and await keywords. Asynchronous programming is fundamentally about
- 5:11Speaker 2: the art of waiting without blocking. In dot net, we
- 5:16Speaker 2: use objects like task to represent a future. It's basically
- 5:19Speaker 2: an operation that will complete at some point. When you
- 5:22Speaker 2: use the awight keyword on a task, you are telling
- 5:25Speaker 2: the runtime, Hey, I need the result of this operation,
- 5:28Speaker 2: but I don't need to hold onto the current thread
- 5:30Speaker 2: while I wait.
- 5:31Speaker 1: So the thread is just instantly returned to the threadpool
- 5:33Speaker 1: to do other useful work.
- 5:34Speaker 2: Exactly, and on the surface, you should care about this
- 5:36Speaker 2: because it has huge benefits. On the client side, it
- 5:39Speaker 2: keeps your UIs totally responsive, the app doesn't freeze. On
- 5:43Speaker 2: the server side, it massively increases scalability.
- 5:46Speaker 1: Because an asp net server isn't just burning through its
- 5:49Speaker 1: finite pool of threads staring blankly at a database connection
- 5:53Speaker 1: waiting for a response.
- 5:54Speaker 2: Right, it can serve other users in the meantime.
- 5:57Speaker 1: But wait, let me push back on this a little bit.
- 6:00Speaker 1: If a weight pauses a method and completely lets go
- 6:03Speaker 1: of the threads so it isn't blocked, where does the
- 6:06Speaker 1: rest of the code actually execute when it wakes up? Like,
- 6:09Speaker 1: how does the local state survive if the thread is
- 6:12Speaker 1: just gone?
- 6:13Speaker 2: That is where the compiler performs some absolute magic. When
- 6:17Speaker 2: you mark a method as async, the c sharp compiler
- 6:20Speaker 2: actually rips that method apart. It rewrites it into a
- 6:23Speaker 2: complex state machine behind the scenes.
- 6:25Speaker 1: Literally rewrites your code.
- 6:27Speaker 2: Literally, it takes all your local variables, which would normally
- 6:30Speaker 2: live on the thread stack and be destroyed when the
- 6:33Speaker 2: thread is released, and it elevates them into fields on
- 6:36Speaker 2: a hidden class that's allocated on the heap.
- 6:38Speaker 1: Okay, so the run time is basically leaving a bookmark
- 6:41Speaker 1: complete with all the local environment variables saved safely in
- 6:44Speaker 1: memory before it steps away.
- 6:45Speaker 2: Yes, and along with that state machine, it captures something crucial.
- 6:49Speaker 2: It's called the synchronization context. Think of the synchronization context
- 6:53Speaker 2: as the specific environment the code was running in before
- 6:56Speaker 2: it paused.
- 6:56Speaker 1: Give you an example of that.
- 6:58Speaker 2: So if you click a button in a window interface,
- 7:01Speaker 2: you are on the UI thread and the context that
- 7:04Speaker 2: gets captured represents that specific UI environment.
- 7:07Speaker 1: Okay, I think I have a way to visualize this.
- 7:10Speaker 1: It's like a restaurant heirstas.
- 7:11Speaker 2: Okay, let's hear it.
- 7:12Speaker 1: You have a table, but you need to step outside
- 7:15Speaker 1: to take a phone call. The hostess doesn't just leave
- 7:18Speaker 1: your table empty for an hour while a huge line
- 7:21Speaker 1: forms at the door.
- 7:22Speaker 2: Right.
- 7:22Speaker 1: She gives the table to someone else, but she captures
- 7:26Speaker 1: your context. She remembers exactly what you ordered and exactly
- 7:29Speaker 1: where you were sitting right right, So when you finish
- 7:31Speaker 1: your call and come back inside, she uses that context
- 7:34Speaker 1: to seat you at an appropriate table to resume your
- 7:36Speaker 1: meal right where you left off.
- 7:37Speaker 2: That is a brilliant way to look at it. Yeah.
- 7:40Speaker 2: When the asynchronous operation, like say a database call, finally finishes,
- 7:44Speaker 2: the state machine uses that captured synchronization context to route
- 7:49Speaker 2: the execution back to where it belongs. Got it So
- 7:51Speaker 2: if it captured a UI context, it cues the rest
- 7:54Speaker 2: of the method to resume specifically on the UI thread.
- 7:57Speaker 2: And that allows you to safely update a textbox or
- 8:00Speaker 2: progress bar without getting cross thread exceptions.
- 8:03Speaker 1: And the text gives some very practical ways to wield
- 8:05Speaker 1: this right, like task delay. Instead of the legacy approach
- 8:09Speaker 1: of thread sleep, which let's be honest, violently blocks a
- 8:13Speaker 1: thread and ruins your scalability, task delay simply sets a timer,
- 8:17Speaker 1: yields the thread back to the pool, and then uses
- 8:20Speaker 1: that state machine to resume when the time is up.
- 8:22Speaker 2: Yeah, and you can orchestrate really complex workflows using combinators
- 8:26Speaker 2: like task dot went all that takes an entire collection
- 8:30Speaker 2: of tasks and gives you back a single task that
- 8:32Speaker 2: completes only when every underlying operation finishes.
- 8:35Speaker 1: Which is perfect for modern micro services. You might need
- 8:39Speaker 1: to gather data from an inventory API, a pricing API,
- 8:43Speaker 1: and a user profile API all at the same time
- 8:46Speaker 1: before you can render a single checkout page exactly.
- 8:49Speaker 2: And the flip side of that, which is equally useful
- 8:51Speaker 2: is task When anything, you give it a bunch of tasks,
- 8:53Speaker 2: but it completes the moment the first one finishes.
- 8:55Speaker 1: Oh right. The book uses the example of pinging multiple
- 8:58Speaker 1: stock quote web service simultaneously. You only care about the
- 9:02Speaker 1: fastest response to give your user the real time price,
- 9:05Speaker 1: so you just take the first one that comes back
- 9:06Speaker 1: and discard the rest.
- 9:08Speaker 2: Right. Super elegant, but as powerful as this aweight and
- 9:13Speaker 2: synchronization context mechanism is, the text really emphasizes that we
- 9:18Speaker 2: are stepping into a very dangerous performance trap if we
- 9:21Speaker 2: don't understand what's happening under the hood.
- 9:23Speaker 1: Okay, here's where it gets really interesting because I actually
- 9:26Speaker 1: struggled with this exact concept when I was reading the source.
- 9:29Speaker 2: Oh yeah, yeah.
- 9:31Speaker 1: If capturing the context is what makes a sinc weate
- 9:33Speaker 1: so seamless, why does the book treat it like a hazard.
- 9:37Speaker 1: Like if I'm building an application, why wouldn't I always
- 9:39Speaker 1: want my code to resume right where it left off.
- 9:42Speaker 1: Jumping around between random background threads seems super confusing.
- 9:45Speaker 2: It does seem confusing at first. Yeah, you have to
- 9:47Speaker 2: look at the physical bottleneck of the UI thread. The
- 9:50Speaker 2: UI thread is just one thungal thread. Capturing and resuming
- 9:54Speaker 2: on that context requires the run time to package up
- 9:57Speaker 2: a continuation message and literally shove it into the UI
- 10:00Speaker 2: thread's message pump. Okay, and the team that built the
- 10:03Speaker 2: Windows runtime actually quantified this exact.
- 10:06Speaker 1: Overhead right the paper cuts issue the one hundred versus
- 10:09Speaker 1: one thousand continuations metric exactly.
- 10:12Speaker 2: They found that if your application is routing about one
- 10:15Speaker 2: hundred continuations per second back to the UI thread, it's
- 10:18Speaker 2: totally fine. The thread can handle drawing the screen and
- 10:22Speaker 2: processing those resume messages. But if you hit around one
- 10:25Speaker 2: thousand continuations per second, you completely flood the message pump.
- 10:29Speaker 2: Oh wow, Yeah, the UI thread becomes so overwhelmed just
- 10:32Speaker 2: processing resume messages that it actually stops drawing the screen.
- 10:36Speaker 2: The application freezes. It's literally death by a thousand paper cuts.
- 10:41Speaker 1: So if I'm writing a core library, say a data
- 10:44Speaker 1: access layer that loops through thousands of records and makes
- 10:47Speaker 1: internal asynchronous calls, and I allow every single one of
- 10:49Speaker 1: those weights to capture the UI context. I'm going to
- 10:52Speaker 1: accidentally lock up the screens of whoever uses my library.
- 10:55Speaker 2: Yes, you'll freeze their app. And the fix for this
- 10:58Speaker 2: is a method called configure weight false. When you pend
- 11:01Speaker 2: to configure weight false to an awaitable task, you are
- 11:04Speaker 2: explicitly overwriting the state machine.
- 11:06Speaker 1: You're telling it to ignore the hostess exactly.
- 11:09Speaker 2: You are telling the compiler do not bother capturing the context.
- 11:12Speaker 2: When this external operation finishes, just grab any available background
- 11:16Speaker 2: thread from the threadpool and continue executing.
- 11:19Speaker 1: Which entirely skips the UI message pump bottleneck. So the
- 11:23Speaker 1: rule of thumb is use configure a weight false rigorously
- 11:27Speaker 1: in all your core library and background code, and only
- 11:30Speaker 1: rely on the default context capturing behavior in your outermost
- 11:34Speaker 1: user interface layer. You know where you actually need to
- 11:37Speaker 1: touch visual elements.
- 11:38Speaker 2: That's the exact architectural boundary you want to establish. But yeah,
- 11:41Speaker 2: configure way is really just a performance optimization. There is
- 11:44Speaker 2: a much bigger trap mentioned in the sources, something that
- 11:47Speaker 2: will flat out destroy your application. Oh boy, the ultimate
- 11:50Speaker 2: sin of modern c shark concurrency ACYNC void.
- 11:54Speaker 1: Yeah, the book practically puts a skull and crossbones next
- 11:57Speaker 1: to ACYNC void. But let's clarify why it even exists.
- 12:01Speaker 1: If it's so incredibly dangerous, why did Microsoft put it
- 12:04Speaker 1: in the language in the first place.
- 12:05Speaker 2: Well, they had to purely for historical backward compatibility. Think
- 12:08Speaker 2: about a classic Windows Forms or WPF application. You have
- 12:12Speaker 2: a button click event handler, right. The signature for that event,
- 12:16Speaker 2: which was mandated by the framework years before acing programming
- 12:19Speaker 2: ever existed, is private void button click. It absolutely must
- 12:25Speaker 2: return void. But what if you want to await a
- 12:27Speaker 2: database call when the user clicks that button.
- 12:30Speaker 1: You can't just change the signature to return a task,
- 12:32Speaker 1: or the framework won't recognize it as an event handler anymore.
- 12:36Speaker 2: Exactly. So, acinc void was introduced as a compromise just
- 12:39Speaker 2: to allow developers to use the await keyword inside legacy
- 12:42Speaker 2: event handlers. But doing so breaks the fundamental air handling
- 12:47Speaker 2: mechanics of the modern language.
- 12:48Speaker 1: Because there's no task object. Let's trace the mechanics of
- 12:52Speaker 1: a failure here, because this is fascinating. When you write
- 12:55Speaker 1: a proper acinc task method and something goes wrong, say
- 12:58Speaker 1: the network just drops what happened to the exception okay.
- 13:01Speaker 2: So normally, the run time catches that exception and neatly
- 13:04Speaker 2: packages it inside the task object that is returned to
- 13:06Speaker 2: the collar. The exception just sits there, completely harmless, until
- 13:10Speaker 2: the calling code actually awaits the task. At that exact moment,
- 13:14Speaker 2: the state machine unwraps the exception and rethrows it, allowing
- 13:17Speaker 2: you to catch it gracefully in a standard try catch block.
- 13:20Speaker 1: But if the method is async void, there is no
- 13:23Speaker 1: task object to act as that protective wrapper.
- 13:25Speaker 2: Right, There's nowhere to store the error. So when an
- 13:28Speaker 2: exception is thrown inside an ACYNC void method, it bypasses
- 13:32Speaker 2: any triketch block you might have set up. It just
- 13:34Speaker 2: blows right past it. The exception escapes the method entirely
- 13:38Speaker 2: and is posted directly to the ambient synchronization context.
- 13:41Speaker 1: And well that's then.
- 13:43Speaker 2: Well. In almost every modern dot net environment, an unhandled
- 13:47Speaker 2: exception hitting the context like that will immediately tear down
- 13:50Speaker 2: the entire application domain. Your app just vanishes.
- 13:53Speaker 1: From the screen, which is terrifying, just poof gone. So
- 13:57Speaker 1: the takeaway is absolute avoid ACYNC void all costs, unless
- 14:01Speaker 1: you are strictly wiring up a legacy UI event handler.
- 14:05Speaker 2: Absolutely.
- 14:06Speaker 1: So we've figured out how to wait for external systems
- 14:08Speaker 1: to respond without locking up our app and how to
- 14:10Speaker 1: avoid crashing the context. But what happens when the delay
- 14:14Speaker 1: isn't external? What happens when our own CPU is the
- 14:17Speaker 1: bottleneck because we have a massive internal data set to crunch.
- 14:20Speaker 2: Ah okay, this is where we pivot from a secretous programming,
- 14:24Speaker 2: which remember, is about ioefficiency, to parallel programming, which is
- 14:29Speaker 2: about CPU throughput. Parallel programming is about taking a massive
- 14:34Speaker 2: amount of computational work and partitioning it across multiple cores
- 14:38Speaker 2: to get it done faster.
- 14:39Speaker 1: Let's ground this in a modern scenario. Instead of just
- 14:42Speaker 1: doing work, imagine we have a massive database query that
- 14:47Speaker 1: takes an hour to run on a single core. We
- 14:50Speaker 1: don't want to just yield the thread and wait an hour.
- 14:52Speaker 1: We want to partition that data set, effectively sharding it
- 14:55Speaker 1: into ten smaller chunks, and hand each chunk to a
- 14:58Speaker 1: different CPU core to PROCESSI simultaneously.
- 15:00Speaker 2: Yeah, that's a perfect architectural analogy. It's like a chef, right.
- 15:04Speaker 2: Acinc is like a chef putting a pianney evident wiping
- 15:06Speaker 2: down the counters while it bakes. Like that, The parallel
- 15:08Speaker 2: processing is like hiring ten sous chefs to chop ten
- 15:11Speaker 2: thousand carrots at the exact same time.
- 15:13Speaker 1: Wow. Yeah.
- 15:13Speaker 2: And the task parallel library gives us two main tools
- 15:16Speaker 2: for this kind of data parallelism, parallel four and pliq
- 15:21Speaker 2: which stands for parallel linq. Both of these tools handle
- 15:25Speaker 2: a complex logic of partitioning your data set and destructing
- 15:28Speaker 2: the chunks to different threads automatically, but.
- 15:30Speaker 1: The sources highlight a critical behavioral difference between how plionq
- 15:35Speaker 1: and the parallel class actually interact with the operating system.
- 15:39Speaker 2: Yes, and it really comes down to aggressiveness. Pli inq
- 15:43Speaker 2: is incredibly elegant to write, but by default it is greedy.
- 15:47Speaker 2: Greedy how it assumes your query is the most important
- 15:50Speaker 2: thing happening on the entire machine, and it will eagerly
- 15:53Speaker 2: try to spin up enough threads to consume every single
- 15:55Speaker 2: CPU core available, which.
- 15:57Speaker 1: Sounds great for speed, but what if this is running
- 15:58Speaker 1: on a web server that is all so trying to
- 16:00Speaker 1: serve hundreds of other user requests at the same time.
- 16:03Speaker 2: Then plimq can actually degrade your overall performance by starving
- 16:07Speaker 2: the OS of threads. It just hogs everything. That is
- 16:10Speaker 2: where parallel for each is often the safer choice. The
- 16:13Speaker 2: parallel class methods are designed to be polite. Yeah. They
- 16:15Speaker 2: dynamically monitor the current CPU load and adjust their thread
- 16:19Speaker 2: usage if the server gets busy with other requests, parallel
- 16:24Speaker 2: for each will actually throttle itself back to play nicely
- 16:27Speaker 2: with the rest of the ecosystem.
- 16:28Speaker 1: But regardless of which tool you use, there is a
- 16:31Speaker 1: golden rule that dictates whether a parallelization will actually speed
- 16:35Speaker 1: up your code or just grind it to a halt,
- 16:37Speaker 1: and that rule is the chunks of work must be
- 16:40Speaker 1: completely independent.
- 16:42Speaker 2: This goes right back to the functional mindset we discussed
- 16:45Speaker 2: at the start. If you shard your data set across
- 16:48Speaker 2: eight cores, but all eight threads are trying to write
- 16:51Speaker 2: their results into a single shared list in memory, you
- 16:54Speaker 2: have to introduce locks to prevent data corruption.
- 16:57Speaker 1: And what happens when eight threads hit a lot at
- 17:00Speaker 1: the exact same time you.
- 17:01Speaker 2: Get locked contention, Seven of those threads instantly freeze and
- 17:04Speaker 2: just stand in line waiting for the first thread to
- 17:06Speaker 2: finish writing. You've just destroyed your parallel efficiency. In fact,
- 17:10Speaker 2: because of the overhead of managing those locks and switching
- 17:12Speaker 2: thread contexts, your code will likely run significantly slower than
- 17:16Speaker 2: if you had just used a single thread in the
- 17:18Speaker 2: first place. Independence is the absolute key to scalability here.
- 17:22Speaker 1: Which perfectly sets up the final evolution the book covers.
- 17:25Speaker 1: We've solved waiting for external IO, we've solved maximizing the
- 17:29Speaker 1: CPU for static data sets, but modern applications rarely deal
- 17:34Speaker 1: entirely in static data. What happens when you aren't iterating
- 17:37Speaker 1: over a fixed array, but instead you are dealing with
- 17:39Speaker 1: an infinite stream of events over time or building a
- 17:42Speaker 1: complex multi step processing pipeline that takes.
- 17:45Speaker 2: Us into reactive extensions generally known as RX and TPL dataflow.
- 17:50Speaker 2: Let's start with RX. If you understand LIANQ, you can
- 17:53Speaker 2: understand RX as basically LANQ two events normal IONQ uses
- 17:58Speaker 2: a pole model static array at memory, and your code
- 18:01Speaker 2: proactively pulls the data out one item at a time.
- 18:04Speaker 1: But RX flips the architecture to a push model.
- 18:07Speaker 2: Exactly With RX, the data might not even exist yet,
- 18:09Speaker 2: and said you define a query and as events happen
- 18:12Speaker 2: in real time, they push themselves through your query logic.
- 18:15Speaker 1: The source material makes a really vital distinction here for
- 18:17Speaker 1: anyone architecting event driven systems. The difference between hot and
- 18:22Speaker 1: cold observables. I found this super helpful.
- 18:25Speaker 2: It's a crucial concept. Yeah. A hot observable is an
- 18:28Speaker 2: event stream that is broadcasting regardless of whether anyone is listening.
- 18:32Speaker 2: Think of mouse movements across a screen or a live
- 18:35Speaker 2: feed of stock market ticks. If your application isn't actively
- 18:39Speaker 2: subscribed to that stream, those events are just gone. They
- 18:42Speaker 2: pass right into the ether.
- 18:43Speaker 1: Contrast that with a cold observable. The book uses an
- 18:46Speaker 1: HTTP download as an example. The server has the data,
- 18:49Speaker 1: but the download stream doesn't actually begin broadcasting until your
- 18:53Speaker 1: code explicitly subscribes to it. It waits for you, right, and.
- 18:56Speaker 2: RX gives developers a unified interface to treat both of
- 18:59Speaker 2: these chaotic streams of events as if they were just
- 19:02Speaker 2: standard collections of data.
- 19:04Speaker 1: And then we have TPL data flow, which tackles a
- 19:06Speaker 1: slightly different architectural problem. Where RX is great for reacting
- 19:10Speaker 1: to events, data flow is designed for building heavy processing
- 19:13Speaker 1: pipelines or meshes.
- 19:14Speaker 2: Yeah. It uses an actor bottle approach. You create distinct
- 19:18Speaker 2: blocks of logic, like say, a transform block to parse
- 19:22Speaker 2: incoming data and an action block to save it to
- 19:24Speaker 2: a database.
- 19:25Speaker 1: You link these blocks together pour data into the top
- 19:27Speaker 1: of the funnel, and the run time automatically handles passing
- 19:30Speaker 1: the data from one block to the next. But as
- 19:33Speaker 1: I was reading this section, I noticed a massive red
- 19:36Speaker 1: flag regarding memory management.
- 19:38Speaker 2: Oh, the unbounded buffers.
- 19:39Speaker 1: Yes, if I have a fast source block downloading thousands
- 19:43Speaker 1: of files and it's pushing them into a slow target
- 19:45Speaker 1: block that has to parse them, won't the slow block
- 19:49Speaker 1: just get completely overwhelmed?
- 19:50Speaker 2: You've identified the exact danger of unbounded buffers. By default,
- 19:55Speaker 2: the input buffer on a data flow block is unbounded,
- 19:58Speaker 2: meaning it will blindly accep every single piece of data
- 20:01Speaker 2: pushed into it, hoarding it all in memory. Right. If
- 20:03Speaker 2: your parsing block is slower than your download block, that
- 20:06Speaker 2: unbounded buffer will just grow and grow until your application
- 20:09Speaker 2: crashes with an out of memory exception.
- 20:11Speaker 1: So how do we implement back pressure? Like, how do
- 20:13Speaker 1: we tell the fast block to just slow down?
- 20:15Speaker 2: The solution is actually a simple configuration property called bounded capacity.
- 20:20Speaker 2: By setting a strict limit on the buffer, say capping
- 20:23Speaker 2: it at ten items, you force the block to reject
- 20:26Speaker 2: new data once it's full. Oh nice, Yeah, this creates
- 20:29Speaker 2: natural back pressure. The system pauses the fast download block
- 20:33Speaker 2: until the slow parsing block has room to accept more data.
- 20:36Speaker 2: It turns a fragile memory hogging script into a robust
- 20:40Speaker 2: self throttling pipeline.
- 20:41Speaker 1: It creates load balancing right out of thin air, which
- 20:45Speaker 1: really brings us full circle. We started this deep dive
- 20:48Speaker 1: looking at the civic ca you know, the chaotic, unpredictable
- 20:51Speaker 1: world of legacy threading that crashed applications and left a
- 20:54Speaker 1: bad taste in our mouths. And step by step we've
- 20:56Speaker 1: seen how c sharp has evolved to solve these problems.
- 20:59Speaker 2: Yeah, we move from men thread allocation to the dynamic threadpool.
- 21:02Speaker 1: We explored the magic of the compiler state machine, letting
- 21:05Speaker 1: us await operations without blocking threads while using configure weight
- 21:08Speaker 1: false to protect the UI message pump and of course
- 21:11Speaker 1: avoiding async void to prevent catastrophic crashes.
- 21:15Speaker 2: We learned how to shatter CPU bottlenecks by partitioning data
- 21:18Speaker 2: with parallel for each and adhering strictly to the rule
- 21:22Speaker 2: of independence to avoid lock contention.
- 21:24Speaker 1: And finally, we looked at how to handle infinite streams
- 21:28Speaker 1: of time based data with RX and how to build
- 21:31Speaker 1: robust self throttling pipelines with TPL data flow.
- 21:35Speaker 2: Really is a profound architectural evolution. I want to leave
- 21:38Speaker 2: you with this thought, based on everything we've uncovered today,
- 21:41Speaker 2: look at the trajectory here. We've moved entirely away from
- 21:44Speaker 2: writing rigid, sequential code that force fully micromanages memory and threads. Instead,
- 21:50Speaker 2: we are utilizing pure functions, immutable data state machines, and
- 21:53Speaker 2: reactive pipelines. If our applications are becoming networks of independent,
- 21:57Speaker 2: self throttling blocks reacting to streams of data, are we
- 22:00Speaker 2: even writing instructions anymore? Or are we truly choreographing a
- 22:04Speaker 2: self balancing digital ecosystem. Think about how adopting that specific
- 22:09Speaker 2: mindset could completely change the resilience and scalability of your
- 22:12Speaker 2: next big project.
- 22:13Speaker 1: Because when you stop fighting the system for control and
- 22:16Speaker 1: start choreographing the ecosystem, you ensure your code never becomes
- 22:20Speaker 1: a legacy pest. Thank you for joining us on this
- 22:22Speaker 1: deep dive into the source material. We will see you
- 22:25Speaker 1: next time.