سؤال

I'm trying to implement a method, that sends HTTP requests to a server and get the response in each two seconds.I need to add a new line to a rich text box which shows response strings. I used "Thread.Sleep(2000)" Method to pause the while loop.

Here is my Code

private void buttonRequest_Click(object sender, EventArgs e)
{
    while (true)
    {
        using (var client = new WebClient())
        {
            var response = client.DownloadString("http://localhost:8181/");
            var responseString = response;
            richTextResponse.Text += responseString + Environment.NewLine;
        }
        Thread.Sleep(2000);
    }
}

But this is not working properly. it pause it self at the beginning and suddenly print the same string more than 5 times. What is the wrong with this. I'm testing the application in localhost. so there is no any connection issue which makes the application slow.

هل كانت مفيدة؟

المحلول

When you are using Thread.Sleep(2000) on UI (main) thread, then your application stops responding to any user actions - it just hangs for 2 seconds. That's a bad idea.

I suggest you to use Timer component for this task. Add timer to your form (you can find it in toolbox) and set its Interval to 2000 milliseconds. Then subscribe to timer's Tick event and do HTTP requests in this event handler. I suggest to use async handler to avoid hanging while waiting for response:

private async void timer_Tick(object sender, EventArgs e)
{
    using (var client = new WebClient())
    {
        Uri uri = new Uri("http://localhost:8181/");
        var response = await client.DownloadStringTaskAsync(uri);
        richTextResponse.Text += response + Environment.NewLine;
    }            
}

And start timer when you click button:

private void buttonRequest_Click(object sender, EventArgs e)
{
    timer.Start();
}

Another option is making your method async and usage of Task.Delay instead of making thread sleep (but I would probably go with timer, which is easier to understand and control):

private async void buttonRequest_Click(object sender, EventArgs e)
{
    while (true)
    {
        using (var client = new WebClient())
        {
            Uri uri = new Uri("http://localhost:8181/");
            var response = await client.DownloadStringTaskAsync(uri);
            richTextResponse.Text += response + Environment.NewLine;
        }

        await Task.Delay(2000);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top