HttpClient how to make a request every 1 second

1

How can I make a request via HttpClient every 1 second?

The server that I send the requests drills the request if it is one after the other with a response: "RequestBlocked"

What I wanted was this: I had 2 requests made, however he would make the first request and return his value, 1 second later he would make the second requisition and so on, can you do something like that?

Code

using (var client = new HttpClient())
{
    var result = await client.GetAsync("http://localhost/api/request.php");
    return result.StatusCode.ToString();
}
    
asked by anonymous 01.08.2017 / 03:29

2 answers

0

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

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

When you start form, it enables the timer.

Following 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());
        }
    }
}

Result:

    
01.08.2017 / 13:32
0

If you need to handle a queue, check out Rovann's answer .

If you want to wait for all Requests to complete and process all at once, it's simpler as follows. 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 it working.

    
01.08.2017 / 15:49