ホーム 暮らし Trying out various sleep methods in C#

Trying out various sleep methods in C#

三浦 拓海 三浦 拓海 • 更新: • 公開: • 読了約 12 分
目次
na7d3b6843888
1. Introduction

Programs usually execute processes extremely quickly. As a result, outputs such as turning on an LED or displaying something on a screen may appear to complete instantaneously to the human eye, making them difficult to perceive. This is where "sleep processing" becomes useful.

Sleep is a function that temporarily pauses program execution for a certain period of time. For example, in a program that repeatedly turns an LED on and off, this allows the human eye to clearly confirm the on and off states.

In this article, I will organize and explain the typical implementation methods and characteristics of sleep processing in C#.

2. What is sleep?

Sleep is a process that temporarily interrupts program execution for a specific duration. However, "pausing" does not mean busy-waiting; instead, it efficiently moves the thread into a waiting state.

A classic example of sleep is "LED blinking," where an LED is repeatedly turned on and off. Because programs run too fast for the human eye to follow, controlling an LED without inserting a sleep would result in it appearing to be constantly lit.

In such scenarios, inserting a sleep immediately after turning on the LED allows the human eye to confirm the lit state.

For example, by inserting a sleep after turning on the LED, the on and off states can be confirmed by the human eye.

3. Examples of sleep implementation methods

I will explain examples of sleep implementation in C#.

3.1 Thread.Sleep

The most common example is the implementation method using Thread.Sleep.

using System;
using System.Threading;

class Program

 static void Main()
 
 while (true)
 
 Console.WriteLine("LED ON ");
 Thread.Sleep(500); // 0.5秒点灯

 Console.WriteLine("LED OFF ");
 Thread.Sleep(500); // 0.5秒消灯

 Console.Clear(); // 画面をクリアして繰り返し見やすく
 
 

In this example, after the LED is turned on, it sleeps for 500ms and then turns the LED off. This allows the human eye to confirm the turning on and off. However, since Thread.Sleep completely stops the thread, it can cause freezing in UI or server applications.

3.2 Asynchronous sleep

Thread.Sleep blocks the thread, which can cause freezing in some cases. By using Task.Delay, you can sleep without being blocked.

using System;
using System.Threading.Tasks;

class Program

 static async Task Main()
 
 while (true)
 
 Console.WriteLine("LED ON ");
 await Task.Delay(500); // 0.5秒点灯(非同期スリープ)

 Console.WriteLine("LED OFF ");
 await Task.Delay(500); // 0.5秒消灯(非同期スリープ)

 Console.Clear(); // 画面クリアで点滅っぽく
 
 

This method waits without blocking the thread, so it can maintain the responsiveness of the UI thread or server. However, since it is an asynchronous method, the method must be defined as async Task.

3.3 GetAwaiter().GetResult()

GetAwaiter().GetResult does not simply stop the thread like Thread.Sleep; instead, it internally waits for the completion of an asynchronous process. Due to this characteristic, it tends to operate more safely with a reduced risk of freezing compared to Thread.Sleep.

using System;
using System.Threading.Tasks;

class Program

 static void Main()
 
 while (true)
 
 Console.WriteLine("LED ON ");
 Task.Delay(500).GetAwaiter().GetResult(); // 0.5秒同期的に待つ(ブロック)

 Console.WriteLine("LED OFF ");
 Task.Delay(500).GetAwaiter().GetResult(); // 0.5秒同期的に待つ(ブロック)

 Console.Clear(); // 画面をクリアして点滅風に見せる
 
 

This program synchronously waits for the completion of the asynchronous Task.Delay process by calling Task.Delay(500).GetAwaiter().GetResult(). As a result, the execution of Console.WriteLine pauses every 0.5 seconds, and by clearing the screen, it makes it appear as if the LED is lit. This method is used when you want to maintain a synchronous processing flow while leveraging the benefits of asynchronous processing.

3.4 Busy loop using StopWatch

A busy loop is a method where the StopWatch class is used to track elapsed time, and the infinite loop is exited once a certain amount of time has passed. An example is shown below.

var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 1000)

 // ずーっと回し続けて待つ

Console.WriteLine("1秒経過!");

This method is effective in situations where high-precision sleep timing is required. However, it is important to note that because no sleep is inserted during the loop, it will continuously consume CPU resources.

4. Conclusion

In this article, we focused on sleep processing and organized the implementation methods in C#. In actual application development, it is important to select the appropriate sleep implementation method according to the intended use and execution environment. I hope you will try out the code provided here, understand the characteristics of each method, and determine the appropriate way to use them.

同じカテゴリの記事

三浦 拓海
コンテンツディレクター 三浦 拓海
プロフィールを見る →

映画と連続ドラマの公開情報を追う担当。配給会社のプレスシートと公式サイトの発表日を確認したうえで執筆します。

おすすめの関連記事