Home > front end >  how to repeat async call
how to repeat async call

Time:06-07

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?

Thank you!

CodePudding user response:

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"));
    }
}

CodePudding user response:

You can use Polly library for such calls. Do not use infinity loop, it is bad practice. Link: https://github.com/App-vNext/Polly Examples: https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly

  • Related