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