Httpclient how to make a request every 1 second

Asked

Viewed 426 times

1

Can I make a request via Httpclient every 1 second?

The server I send requests blocks the request if it is one behind the other with an answer: "Requestblocked"

What I wanted was this: I had two requests, however he would make the first request and return its value, 1 second later he would make the second request and so on, have to do something like this?

Code

using (var client = new HttpClient())
{
    var result = await client.GetAsync("http://localhost/api/request.php");
    return result.StatusCode.ToString();
}
  • 2

    What is your young project doing, windows Forms ? please give more details. Also put the code you already have ready. The question as it stands will certainly be closed because it is too broad, or not clear enough. Enjoy the tour of the site: https://answall.com/tour

  • Hi, I use winform,

2 answers

0


For this you can use a control Timer, which can be dragged directly from Toolbox.

Set the property Interval for 1000 (milliseconds) = 1 second, and manipulate the event Tick, placing the request inside it.

When you start the form, enable the timer.

Follow example code:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Request();

        int count = results.Count;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        timer1.Enabled = true;
    }

    Queue<string> results = new Queue<string>();
    private async void Request()
    {
        using (var client = new HttpClient())
        {
            var result = await client.GetAsync("http://google.com");
             results.Enqueue(result.StatusCode.ToString());
        }
    }
}

Upshot:

Resultado código

  • Since he’s gonna use the GetAsync Anyway, it’s no longer simple to use await Task.Delay(1000) instead of a Timer just for that?

  • @Vítormartins if you can, put an answer to what the code would look like, I’m interested too, thank you

  • 1

    Thank you for the reply :)

0

If you need to treat a queue, see the response from Rovann.

If you want to wait for all Requests to complete and process all at once, it’s simpler the way below. I personally find timers quite unpredictable.

public static async Task<IDictionary<string, string>> Requests(params string[] urls)
{
    var dictionary = new Dictionary<string, string>();

    using (var client = new HttpClient())
    {
        foreach(string url in urls)
        {
            var result = await client.GetAsync(url);                
            dictionary.Add(url, result.StatusCode.ToString());

            await Task.Delay(1000);
        }
    }

    return dictionary;
}

See working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.