--- lang: ja-jp breaks: true --- # C# Task `async/await` と `Wait()` の処理速度比較 2021-12-30 ## 1. `async/await` ※遅い ```csharp= private async void button2_Click(object sender, EventArgs e) { var cancellationToken = new CancellationTokenSource(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { var task = new Task(() => { }); task.Start(); await task.WaitAsync(cancellationToken.Token); } sw.Stop(); AppendText(sw.Elapsed.ToString()); } ``` ## 2. `async/await` `ConfigureAwait(false)` ※圧倒的に早い ```csharp= private async void button2_Click(object sender, EventArgs e) { var cancellationToken = new CancellationTokenSource(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { var task = new Task(() => { }); task.Start(); await task.WaitAsync(cancellationToken.Token) .ConfigureAwait(false); } sw.Stop(); AppendText(sw.Elapsed.ToString()); } ``` ## 3. `Wait()` ※圧倒的に早い ```csharp= private void button3_Click(object sender, EventArgs e) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { var task = new Task(() => { }); task.Start(); task.Wait(); } sw.Stop(); AppendText(sw.Elapsed.ToString()); } ``` ## 結果 | 項番 | 内容 | 処理速度 | | -------- | -------- | -------- | | 1 | `async/await` | 00:00:36.4577603 | | 2 | `async/await` `ConfigureAwait(false)` | 00:00:01.6336271 | | 3 | `Wait()` | 00:00:01.4675350 | :::info * 環境:net6.0-windows * WinFormから実行 ::: ###### tags: `C#` `Task` `async` `await` `Wait()` `処理速度` `CancellationTokenSource` `ConfigureAwait` `SynchronizationContext`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up