Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to repeat async call

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading