liveBook · Manning

Context switching

As explained in C# Concurrency: Asynchronous and multithreaded programming

A context switch is the act of saving one thread's execution state and loading another thread's state so the processor can run it.

Context switching saves one thread’s execution state and loads another thread’s state so a CPU can alternate between sequences of work. The operating system also removes blocked threads from CPU scheduling until file, network, or inter-thread waiting completes. section 1.1

Context switching has practical costs and purposes:

  • The CPU timer can trigger a switch between threads, creating the appearance of simultaneous execution on one CPU. section 1.1 section 1.6
  • Each switch adds overhead because the processor must preserve the current thread’s status and restore another’s. section 1.1 section 1.6
  • Blocking operations release the CPU rather than wasting time scheduling a thread that cannot proceed. section 1.1
  • Asynchronous programming avoids waiting on the thread during external operations, resuming processing after completion notification. section 1.6

The pizzeria analogy

A cook alternates between pizzas when timers beep, putting one aside and restoring another task. The repeated storing and picking up mirrors context switching, while waiting for an oven resembles a blocked thread. section 1.1

Figure 1.2 Single-threaded versus multithread with multiple requests

Compare single-threaded and multithreaded request flows to see why switching supports multiple outstanding requests. section 1.1

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains state saving, restoration, timer-driven switching, blocked states, and overhead without presenting implementation code.
Examples
Uses a multitasking cook, pizza timers, file reads, network access, and multiple request flows.
What it assumes
Defines threads, blocking operations, and asynchronous programming while assuming basic awareness of CPU execution.
What you can do after
Evaluate why thread switching costs resources and when nonblocking asynchronous work can release a waiting thread.
How it connects
Connects context switching to threads, multithreading, blocking operations, asynchronous programming, and CPU scheduling.

Also explained in

Compare how 9 books explain context switching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.