JavaRush/Courses/C# SELF/The problem of blocking calls

The problem of blocking calls

59 level, 0 lecture
Open

1. Introduction

Blocking call — any call that “blocks” the execution of a thread until some operation completes. Usually this is:

  • Reading or writing data (for example, from disk).
  • A long database or network request.
  • A call to a third-party library that works “slowly”.

At those moments the thread just stands there, shuffling its feet and waiting: “So? When's the answer?”

Real-life example

// Your main logic
Console.WriteLine("Waiting for server response...");
string response = CallServer(); // everything's stuck here!
Console.WriteLine("Server replied: " + response);

Until the server responds, your thread is "stalled" — it can't do anything else!

How it looks in apps

In different app types this shows up differently. In a console program it looks like it just “froze” — the cursor stops blinking and there's no reaction. In a GUI, like WinForms or WPF, the window suddenly stops responding, you get the familiar “not responding”, and the user is ready to curse both your app and your name. On servers it's even worse: one stuck thread means one less served user.

2. Blocking calls in C# in practice

Let's "feel" the situation hands-on using a demo project. Suppose we have a magic ball app. It might contain, for example, this snippet:

Console.WriteLine("Enter your question for the magic ball:");
string question = Console.ReadLine(); // blocking call: waiting for input!
Console.WriteLine("Thinking about the answer...");
Thread.Sleep(5000); // emulation of long work
Console.WriteLine("Answer: try again tomorrow!");
  • Console.ReadLine() — waits for user input as long as needed (blocking the thread).
  • Thread.Sleep(5000) — artificially pauses, freezing the thread.

Question: What's wrong if we're just dealing with a console app?

Answer: In a console app it's not that critical — your user expects to wait. But what if the user isn't alone? What if it's a server getting 1000 requests at once? Or a GUI app where the user expects UI responsiveness, not your philosophical musings?

Example: UI blocking

// In WinForms button handler:
private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Loading...";
    DoHeavyWork(); // heavy operation (e.g., DB query)
    label1.Text = "Done!";
}

Problem: While DoHeavyWork runs, the window doesn't update the interface, doesn't respond to keyboard or mouse, and doesn't repaint. If the user tries to close the window — Windows will show "not responding" and offer to terminate the task.

3. The main pain of the multithreaded world

Problems of blocking calls

  • Wasted resources. Each thread (Thread) in .NET is a fairly “heavy” object. The OS allocates stack memory for it (typically 1 MB), handles, synchronization, etc. If a thread is “idle” (waiting for a file or network), it's doing useless work (“doing nothing, eating memory”).
  • Limited threads. Server apps usually have a thread pool. If all threads block — new requests aren't handled. For example, in ASP.NET: if all available threads wait for the database, the site “freezes” for all new users.
  • Poor UI responsiveness. In GUI apps the window stops responding even to “close” when the UI thread is blocked.
  • Performance degradation. The more threads are blocked, the more context switches, OS load, and the slower the whole machine runs.

Typical sources of blocking calls

Let's look at what calls can block a thread “out of nowhere”:

  • Network operations: calling APIs, downloading files, fetching updates.
  • Disk/file system: reading or writing large files.
  • Databases: long SQL queries or even local DB calls.
  • User input: long ReadLine — small thing, but still blocks.
  • Thread.Sleep, Task.Delay: artificially “freeze” the thread.
Example (downloading data from a website)
using System.Net.Http;

HttpClient client = new HttpClient();
string result = client.GetStringAsync("https://google.com").Result; // blocking synchronous call!
Console.WriteLine(result);

What's happening here? The .Result blocks the thread until the response arrives!

4. How to tell your call is blocking the thread?

Simple: if a method doesn't return control until it finishes its work (waiting, input, network, disk) — it's a blocking call.

  • Methods with Thread.Sleep, Task.Wait, .Result, .Wait() — block.
  • Methods that do read/write without async — also block.
  • A “hung” window or a stalled server — a common sign.

Visual: Flowchart of a blocking call

+-------------------+
| Method start      |
+-------------------+
         |
         v
+-------------------+
| Call blocking     |
| method (e.g. file |
| read)             |
+-------------------+
         |
         v
+-------------------+
| Wait for the      |
| operation to end  |
+-------------------+
         |
         v
+-------------------+
| Return from the   |
| method and continue|
+-------------------+

5. Why blocking calls are bad in server apps

Most modern apps are networked or server-side. Even games load stuff from servers. If you're building a website, you'll definitely deal with network and disk.

Imagine your server handles 1000 requests per second. Each request needs to talk to the database. You write:

// Web handler
string data = db.ReadDataSync(); // Synchronous blocking!
return new Response(data);

While the DB is being queried, the thread is just bored and waiting. One request — fine. But when many pile up, all threads get tied up. New ones can't get in and queue up. The server becomes not a machine but a long line where everyone stands and waits for someone to move a bit.

Illustration: "Synchronous request handling"

Request 1: grabbed thread -> waits for DB -> freed
Request 2: grabbed thread -> waits for DB -> freed
...
Request 100: no free threads, waits in queue...

6. Asynchrony — the cure for blocking calls

To fight blocking, use asynchronous calls. In C# the magic words are async and await.

They allow you to:

  • Not block the thread (especially valuable for UI or server threads).
  • Not waste resources senselessly.
  • Improve UI responsiveness.
  • Not “hold” a thread while a slow operation runs.

Note: we don't start with async everywhere because it requires understanding threads and blocking. Now that you feel the pain of blocking calls, the async approach will feel like sweet relief for both your brain and your users.

Table: What blocks and what doesn't?

Method/Call Blocks thread Suitable for UI/Server
Console.ReadLine()
Yes No
Thread.Sleep(1000)
Yes No
File.ReadAllText()
Yes No
Task.Delay(1000).Wait()
Yes No
HttpClient.GetStringAsync().Result
Yes No
await File.ReadAllTextAsync()
No Yes
await Task.Delay(1000)
No Yes
await HttpClient.GetStringAsync()
No Yes

NB: await works only inside an async function (async Task ...), which we'll cover in detail in upcoming lectures.

7. Legendary mistakes when dealing with blocking calls

“I block the UI — the user hates everything”

private void btnLoad_Click(object sender, EventArgs e)
{
    var data = BigFileReader.Read(@"C:\huge.dat"); // blocking call!
    textBox1.Text = data;
}

Until the huge file is read — the window “hangs”.

“Server hangs — clients run away”

public IActionResult Download()
{
    var content = File.ReadAllBytes("bigfile.zip"); // sync, slow, blocks ASP.NET thread!
    return File(content, "application/zip");
}

Small servers (e.g., on free hosting) might simply “crash” with this approach.

“Async method + .Wait()/.Result = synchronous death”

public void LoadData()
{
    var result = DoAsyncWork().Result; // Blocks the thread!
}

.Result and .Wait() turn even nice async code into plain blocking calls.

2
Task
C# SELF,  59 level,  0 lecture
Locked
Emulating a blocking call with a pause
Emulating a blocking call with a pause
Комментарии
  • популярные
  • новые
  • старые
Для того, чтобы оставить комментарий Вы должны sign in
This page has no comments yet