Skip to main content

C# example using the Generator pattern that yields results asynchronously from a remote web API.

// -----------------------------------------------------------------------------
// Program.cs
// https://github.com/PacktPublishing/C-8-and-.NET-Core-3.1-Recipes-2nd-Edition-/blob/master/Section%202/2.5_AsyncStreams/AsyncStreams/Program.cs
// -----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace AsyncStreams
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await foreach(var user in UserGenerator.GetUser())
            {
                Console.WriteLine(user);
            }
        }
    }
}

// -----------------------------------------------------------------------------
// UserGenerator.cs
// https://github.com/PacktPublishing/C-8-and-.NET-Core-3.1-Recipes-2nd-Edition-/blob/master/Section%202/2.5_AsyncStreams/AsyncStreams/UserGenerator.cs
// -----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;

namespace AsyncStreams
{
    public static class UserGenerator
    {
        private const string url = "https://jsonplaceholder.typicode.com/users";

        private static HttpClient _http = new HttpClient();

        public async static IAsyncEnumerable<User> GetUser()
        {
            for(int i = 0; i < 10; i++)
            {
                var response = await _http.GetStringAsync($"{url}/{i + 1}");

                var currentUser = JsonSerializer.Deserialize<User>(response, new JsonSerializerOptions()
                {
                    PropertyNameCaseInsensitive = true
                });

                yield return currentUser;
            }
        }
    }
}

// -----------------------------------------------------------------------------
// User.cs
// https://github.com/PacktPublishing/C-8-and-.NET-Core-3.1-Recipes-2nd-Edition-/blob/master/Section%202/2.5_AsyncStreams/AsyncStreams/User.cs
// -----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace AsyncStreams
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Website { get; set; }

        public override string ToString()
        {
            return $"{Name} - {Email}";
        }
    }
}