Answer the question
In order to leave comments, you need to log in
How to increase the number of requests to the server in the minimum time?
Hello, I immediately apologize for my stupidity (I am just starting to learn c #), but it is very necessary to write this program. The problem is that I send a request to the server:
private string GET(string Url)
{
WebRequest req = WebRequest.Create(Url);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string Out = sr.ReadToEnd();
sr.Close();
return Out;
}
Answer the question
In order to leave comments, you need to log in
Try using HttpClient :
private async Task<string> Get(string url)
{
using (var client = new HttpClient())
{
using (var r = await client.GetAsync(new Uri(url)))
{
return await r.Content.ReadAsStringAsync();
}
}
}
private void Get(string url)
{
Task.Run(async () =>
{
WebRequest req = WebRequest.Create(url);
WebResponse resp = await req.GetResponseAsync();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string result = await sr.ReadToEndAsync();
sr.Close();
// передаем результат
ResultCallback(url, result);
});
}
private void ResultCallback(string url, string result)
{
// выводим в консоль результат
Console.WriteLine(url);
Console.WriteLine(result);
}
private void Get(string url)
{
Task.Run(async () =>
{
using (var client = new HttpClient())
{
using (var r = await client.GetAsync(new Uri(url)))
{
string result = await r.Content.ReadAsStringAsync();
ResultCallback(url, result);
}
}
});
}
private void Get(string url)
{
// выполняем запрос в отдельном потоке
Task.Run(() =>
{
WebRequest req = WebRequest.Create(url);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string result = sr.ReadToEnd();
sr.Close();
// передаем результат в функцию обратного вызова
ResultCallback(url, result);
});
}
private void ResultCallback(string url, string result)
{
Console.WriteLine(url);
Console.WriteLine(result);
}
private void Get(string url)
{
// создаем поток
var t = new Thread(() =>
{
WebRequest req = WebRequest.Create(url);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string result = sr.ReadToEnd();
sr.Close();
ResultCallback(url, result);
});
// запускаем
t.Start();
}
private void ResultCallback(string url, string result)
{
Console.WriteLine(url);
Console.WriteLine(result);
}
I'll edit the first answer to your question.
await - synchronizes the request, and as I understand it, you want several requests in parallel.
maybe so
var task1= Get("https://toster.ru/q/470457");
var task2= Get("https://toster.ru/q/470458");
var task3= Get("https://toster.ru/q/470459");
var result1=task1.Result;
var result2=task2.Result;
var result3=task3.Result;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question