It turns out that you generate a bunch of threads, and the more threads, the slower the program works. I will explain - in a multithreaded application, switching between threads is an expensive operation in terms of resources and time. Thus, the more threads - the more switching between threads, the more time is spent on switching and less on useful work. In other words, if you create a lot of threads, your program will not run faster, but most likely it will just hang, since all the time it will be spent on switching between threads.
The thing is that now, when you create 100,500 threads, most of the time each thread either waits for a response from the server, or waits for Thread.Sleep () - that is, in fact, stands idle. If you redo for asynchronous requests, then you don’t understand a lot of threads, since an asynchronous operation doesn’t take a thread at all. And once there are fewer threads, then fewer switches between them, and, as a result, everything should work faster.
That is, you need to:
- Try sending requests asynchronously.
- use to send an HttpClient
As an example (I cannot vouch for correctness - I did not launch it, but the idea should be clear)
public class Request { private bool _runned = false; public async void Start() { _runned = true; while(_runned) { await SendRequest("http://google.com"); await Task.Delay(1000); } } public void Stop() { _runned = false; } private static async Task<string> SendRequest(string url) { using(var client = new HttpClient()) { var result = await client.GetStringAsync(url); // do smthg return result; } } }