skip to Main Content

I have a program which does a simple http get in an async call and writes it to the console:

using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Hello 
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
       static async Task Main(string[] args)
        {
            await ProcessRepositories();
        }
        private static async Task ProcessRepositories()
        {
            client.DefaultRequestHeaders.Accept.Clear();
            var stringTask = client.GetStringAsync("https://localhost:8080");
            var msg = await stringTask;
            Console.Write(msg);                
        }
    }
}

How could I repeat the whole process to make it write it to the console until a button is pressed?

3

Answers


  1. class Program
    {
        private static readonly HttpClient client = new HttpClient();
        static async Task Main(string[] args)
        {
            while (true)
            {
                var consoleKey = Console.ReadKey().Key;
                if (consoleKey == ConsoleKey.Enter) // if pressed Enter
                    await ProcessRepositories();
                else if (consoleKey == ConsoleKey.Escape) // if pressed Esc
                    break;
            }
    
            Console.WriteLine("Finish");
        }
    
        private static async Task ProcessRepositories()
        {
            client.DefaultRequestHeaders.Clear(); // idk why you cleaning headers, but OK
            Console.Write(await client.GetStringAsync("https://localhost:8080"));
        }
    }
    
    Login or Signup to reply.
  2. You can use Polly library for such calls. Do not use infinity loop, it is bad practice.

    Here is an example about retry with exponential backoff.

    Login or Signup to reply.
  3. To keep processing data until a key is pressed;

    private static readonly HttpClient client = new HttpClient();
    
    public static async Task Main(string[] args)
    {
        var tokenSource = new CancellationTokenSource();
        var process = ProcessRepositories(tokenSource.Token);
    
        Console.ReadKey();
    
        tokenSource.Cancel();
        try
        {
            await process;
        }
        catch (OperationCanceledException) { }
    }
    
    private static async Task ProcessRepositories(CancellationToken token = default)
    {
        while (!token.IsCancellationRequested)
        {
            Console.Write(await client.GetStringAsync("https://localhost:8080", token));
            await Task.Delay(30_000);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search