Skip to content

Instantly share code, notes, and snippets.

@hsytkm
Created January 4, 2021 03:59
Show Gist options
  • Save hsytkm/f22d2b8ec214f06e94e5621f3147f272 to your computer and use it in GitHub Desktop.
Save hsytkm/f22d2b8ec214f06e94e5621f3147f272 to your computer and use it in GitHub Desktop.
Linq in the asynchronous era
// 非同期時代のLINQ http://neue.cc/2013/12/04_435.html
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
static string GetName(int id) => $"Hoge {id}";
static async Task<string> GetNameAsync(int id)
{
await Task.Delay(TimeSpan.FromMilliseconds(5000)); // 適当に待機
return $"Hoge {id}";
}
// 以後idsと出てきたらこれのこと指してるとします
var ids = Enumerable.Range(1, 4);
// 同期バージョン
var names1 = ids.Select(x => new { Id = x, Name = GetName(x) }).ToArray();
Console.WriteLine(string.Join(',', names1.Select(n => $"{n.Name}")));
// 非同期バージョン1
var names2 = await Task.WhenAll(ids.Select(async x => new { Id = x, Name = await GetNameAsync(x) }));
Console.WriteLine(string.Join(',', names2.Select(n => $"{n.Name}")));
// 非同期バージョン2
var names3 = await ids.Select(async x => new { Id = x, Name = await GetNameAsync(x) }).WhenAll();
Console.WriteLine(string.Join(',', names3.Select(n => $"{n.Name}")));
public static class TaskEnumerableExtensions
{
public static Task WhenAll(this IEnumerable<Task> tasks) => Task.WhenAll(tasks);
public static Task<T[]> WhenAll<T>(this IEnumerable<Task<T>> tasks) => Task.WhenAll(tasks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment