5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#の非同期処理について調べてみた / I looked into asynchronous processing in C# (日本語 / 英語)

Last updated at Posted at 2024-12-24

image.png

日本語

こんばんわ!
Advent Calendar 2024に参加してまして、25日目の最終記事を書いていこうと思います。
題材は「C# Advent Calendar 2024」ということで、非同期処理について書いていこうと思います。

非同期処理とは?

非同期処理は、プログラムの応答性を向上させたり、リソースを効率的に活用するために欠かせない技術です。C# では async と await を使った非同期プログラミングが簡単に実現できます。

・応答性の向上

ユーザーインターフェースがフリーズしにくくなる。

・効率的なリソース利用

待ち時間を有効活用できる。

・並列実行が可能

他の処理を同時進行で実行できる。

使用例

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Task task1 = DoTaskAsync("タスク1", 2000);
        Task task2 = DoTaskAsync("タスク2", 1000);

        await Task.WhenAll(task1, task2);
        Console.WriteLine("全てのタスクが完了しました。");
    }

    static async Task DoTaskAsync(string taskName, int delay)
    {
        await Task.Delay(delay);
        Console.WriteLine($"{taskName} が完了しました。");
    }
}

出力はタスク2→タスク1の順となります。

こんな風に処理の並行実行もできます!
使えば、より可用性の高いシステムが作りこめます

ここまでです。
読んでいただきありがとうございます

ENGLISH

Good evening!
I am participating in Advent Calendar 2024 and I am going to write the final article for the 25th day.
The subject is “C# Advent Calendar 2024” and I will write about asynchronous processing.

What is asynchronous processing?

Asynchronous processing is an essential technique for improving program responsiveness and efficient use of resources.

・Improved responsiveness

The user interface is less likely to freeze.

・ Efficient resource utilization

Effective use of waiting time is possible.

・Parallel execution possible

Other processes can be executed concurrently.

Usage Example

using System; using System.
Tasks; using System.

class Program
{
    static async Task Main()
    {
        Task task1 = DoTaskAsync("Task 1", 2000);
        Task task2 = DoTaskAsync("task2", 1000);

        await Task.WhenAll(task1, task2);
        Console.WriteLine("All tasks completed.") ;
    }

    static async Task DoTaskAsync(string taskName, int delay)
    {
        await Task.Delay(delay);
        Console.WriteLine($"{taskName} has completed.") ;
    }
}

The output will be in the order of Task 2, then Task 1.

You can also execute processes in parallel like this!
You can create a system with higher availability by using it!

That's all for now.
Thank you for reading!

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?