🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

async and await: Not Freezing While Waiting for a Slow Device

You simulate delayed measurement readings with Task, async and await, and learn to read several devices at once, add a timeout, and why the user interface does not freeze.

When you ask an energy analyser for data over Modbus, the answer does not come at once; waiting half a second on a serial line, or a second for a device on the network, is normal. What the program does during that time matters. In a console program a few seconds of waiting is annoying; in a windowed program the window freezes, "Not responding" appears, and the user closes the program. async and await turn waiting from "standing still" into something useful: the program carries on with other work while it waits for the answer. In this lesson we will use simulation methods that wait and then return a value, instead of real devices.

Synchronous reading: wait and stand still

Let us see the problem first. Each reading takes 1 second. Thread.Sleep stops the program completely for that time:

using System.Diagnostics;

var timer = Stopwatch.StartNew();
double a = Read("CH1");
double b = Read("CH2");
double c = Read("CH3");
Console.WriteLine($"Values: {a} | {b} | {c}");
Console.WriteLine($"Elapsed: about {timer.Elapsed.TotalSeconds:F0} s");

static double Read(string channel)
{
    Thread.Sleep(1000);                 // wait for the device (stops everything)
    return channel switch { "CH1" => 3.3, "CH2" => 4.9, _ => 1.2 };
}
Values: 3.3 | 4.9 | 1.2
Elapsed: about 3 s

Even though the three devices are independent, they were waited for one after another, and the program could do nothing else for those 3 seconds. Stopwatch is a ready-made class that measures elapsed time.

Task, async and await

Task<double> means "a job that will produce a double later"; you can think of it as a parcel tracking number. When you put async in front of a method, you can use await inside it. await waits for a task, but it does not block the thread while waiting; it gives control back to the caller. When the task finishes, the method continues from the line where it stopped. In top-level code you can write await directly.

Task<double> job = ReadAsync("CH1", 1000);      // start the reading, do not wait

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine($"Meanwhile the screen is updating... {i}");
    await Task.Delay(200);
}

double value = await job;                         // now get the result
Console.WriteLine($"CH1 = {value} V");

static async Task<double> ReadAsync(string channel, int delayMs)
{
    await Task.Delay(delayMs);          // wait, but free the thread
    return channel switch { "CH1" => 3.3, "CH2" => 4.9, _ => 1.2 };
}
Meanwhile the screen is updating... 1
Meanwhile the screen is updating... 2
Meanwhile the screen is updating... 3
CH1 = 3.3 V

The reading started, but the program went into the loop without waiting for it to finish. While the device was "answering", three lines were printed. Only on the line where we really needed the result did we wait with await job. By convention, the names of asynchronous methods end in Async.

Several readings at once: Task.WhenAll

If you have three independent devices, you can start all three and wait for all of them to finish. The waits overlap; the total time equals the slowest device.

using System.Diagnostics;

var timer = Stopwatch.StartNew();
Task<double> t1 = ReadAsync("CH1", 1000);
Task<double> t2 = ReadAsync("CH2", 1000);
Task<double> t3 = ReadAsync("CH3", 1000);

double[] results = await Task.WhenAll(t1, t2, t3);
Console.WriteLine($"Values: {string.Join(" | ", results)}");
Console.WriteLine($"Elapsed: about {timer.Elapsed.TotalSeconds:F0} s");

static async Task<double> ReadAsync(string channel, int delayMs)
{
    await Task.Delay(delayMs);
    return channel switch { "CH1" => 3.3, "CH2" => 4.9, _ => 1.2 };
}
Values: 3.3 | 4.9 | 1.2
Elapsed: about 1 s

The same three readings took about 1 second this time instead of 3. The array returned by WhenAll comes in the order you passed the tasks; it does not matter which one finished first.

Timeout: a device that does not answer

In the field a device may never answer. To avoid waiting forever, you set a time limit with CancellationTokenSource. When the time is up, the waiting operation is cancelled and an exception is thrown:

using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
try
{
    await Task.Delay(2000, cancel.Token);   // a slow device that answers in 2 seconds
    Console.WriteLine("Answer received");
}
catch (TaskCanceledException)
{
    Console.WriteLine("Timeout: the device did not answer within 500 ms");
}
Timeout: the device did not answer within 500 ms

Most asynchronous methods in real communication libraries accept a cancellation token (CancellationToken) parameter like this.

Why doesn't the user interface freeze?

In a windowed program (WinForms, WPF), all screen drawing and clicks are handled on a single UI thread. This thread keeps looping and asking "is there a new event?". If you write Thread.Sleep(3000) in a button's event handler, this loop stops for 3 seconds: the window cannot be redrawn or dragged, and clicks wait in the queue. await, on the other hand, gives control back to the loop as soon as the wait begins; the window stays alive. When the wait is over, the rest of the method runs on the UI thread again, so you can safely update the label.

// Bad: the window freezes for 3 seconds
private void btnRead_Click(object sender, EventArgs e)
{
    Thread.Sleep(3000);
    lblValue.Text = "3.3 V";
}

// Good: the window keeps responding
private async void btnReadAsync_Click(object sender, EventArgs e)
{
    lblValue.Text = "Reading...";
    double v = await ReadAsync("CH1", 3000);
    lblValue.Text = $"{v} V";
}

This is a fragment taken from inside a WinForms form; it does not run on its own in the console. async void is acceptable only here, in event handlers; every other asynchronous method you write should return Task or Task<T>.

Common mistakes

  • Waiting with .Result or .Wait(): These turn asynchronous work back into synchronous waiting and block the thread. In a UI program they freeze the window and can even lock the program up for good (a deadlock). Always use await.
  • Forgetting await: If ReadAsync("CH1"); is written on its own, the task starts but nobody waits for it; the compiler gives only a warning. An error inside it can also be lost silently.
  • Thread.Sleep inside an async method: Even in an async method, Thread.Sleep blocks the thread. To wait asynchronously, write await Task.Delay(...).

Exercise

Read four temperature sensors at the same time. The sensors answer after 300, 800, 500 and 600 ms respectively and return 23.5, 24.0, 22.5 and 25.0 degrees. Each sensor prints a line when it answers. When all have arrived, print the average and show whether the readings ran in parallel or one after another by checking whether the total time was under 1.5 seconds.

Hint: Collect the tasks in a List<Task<double>> and wait with await Task.WhenAll(list). One after another, it would take 300 + 800 + 500 + 600 = 2200 ms.

Solution

using System.Diagnostics;

var timer = Stopwatch.StartNew();
var jobs = new List<Task<double>>
{
    ReadSensorAsync("T1", 23.5, 300),
    ReadSensorAsync("T2", 24.0, 800),
    ReadSensorAsync("T3", 22.5, 500),
    ReadSensorAsync("T4", 25.0, 600)
};

double[] values = await Task.WhenAll(jobs);
Console.WriteLine($"Average: {values.Average():F2} C");
Console.WriteLine(timer.ElapsedMilliseconds < 1500
    ? "Read in parallel (took as long as the slowest sensor)"
    : "Read one after another");

static async Task<double> ReadSensorAsync(string name, double value, int delayMs)
{
    await Task.Delay(delayMs);
    Console.WriteLine($"{name} answered: {value} C");
    return value;
}
T1 answered: 23.5 C
T3 answered: 22.5 C
T4 answered: 25 C
T2 answered: 24 C
Average: 23.75 C
Read in parallel (took as long as the slowest sensor)

The sensors showed up on screen not in list order but by response time: the fastest first. The total time was about 800 ms, as long as the slowest sensor.

Your program now stays smooth even while waiting for slow devices. With this lesson the advanced part of the C# course is complete; the next step is to turn what you have learned into a windowed measurement tool with WinForms.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What is the key difference between await Task.Delay(1000) and Thread.Sleep(1000)?
2. If you start three independent readings that each take 1 second and wait for them with Task.WhenAll, roughly how long does it take in total?
3. When is the async void return type acceptable?

Mark it when you finish: your progress is saved and you earn +20 XP.

// Final exam and certificate

20 random questions from the lessons, 30 minutes, pass mark 70%. If you pass, you get a verifiable certificate of achievement (with a QR code).

Take the final exam

Tip: ← → keys let you move between lessons.