Created Post function with threading

This commit is contained in:
2025-03-21 09:28:37 +01:00
parent 091f18c870
commit 646a75e959

View File

@@ -3,7 +3,7 @@
//Body //Body
//Per quanto tempo fare il test //Per quanto tempo fare il test
//Metodo HTTP //Metodo HTTP
//Numero Thread(?) //Numero Thread
using System.Diagnostics; using System.Diagnostics;
@@ -22,6 +22,7 @@ internal class Program
long lTime; long lTime;
string? yn; string? yn;
int nThreads; int nThreads;
int nThread = 1;
Stopwatch sw; Stopwatch sw;
using var client = new HttpClient(); using var client = new HttpClient();
@@ -96,7 +97,6 @@ internal class Program
switch (methodHttp.ToUpper()) switch (methodHttp.ToUpper())
{ {
case "GET": case "GET":
int nThread = 1;
while (nThreads != 0) while (nThreads != 0)
{ {
Thread thread = new Thread(() => { Get(url, lTime); }); Thread thread = new Thread(() => { Get(url, lTime); });
@@ -106,18 +106,19 @@ internal class Program
nThreads--; nThreads--;
nThread++; nThread++;
} }
break; break;
case "POST": case "POST":
if (!string.IsNullOrEmpty(body)) if (!string.IsNullOrEmpty(body))
{ {
sw = Stopwatch.StartNew(); while (nThreads != 0)
while (sw.ElapsedMilliseconds < lTime)
{ {
Console.WriteLine("POST" + url + $" [{sw.ElapsedMilliseconds / 1000.0} s]"); Thread thread = new Thread(() => { Post(url, lTime, body); });
client.PostAsync(url, new StringContent(body)); thread.Name = nThread.ToString();
thread.Start();
Console.WriteLine($"Thread {thread.Name} started.");
nThreads--;
nThread++;
} }
sw.Stop();
} }
break; break;
} }
@@ -129,10 +130,23 @@ internal class Program
Stopwatch sw = Stopwatch.StartNew(); Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < lTime) while (sw.ElapsedMilliseconds < lTime)
{ {
Console.WriteLine("GET " + url + $" [{sw.ElapsedMilliseconds / 1000.0} s]" + $"[# {Thread.CurrentThread.Name}]"); Console.WriteLine("GET " + url + $" [{sw.ElapsedMilliseconds / 1000.0} s]" + $"[# {Thread.CurrentThread.Name}]");
var response = client.GetAsync(url); var response = client.GetAsync(url);
Console.WriteLine(response.Result.StatusCode); Console.WriteLine(response.Result.StatusCode);
} }
sw.Stop(); sw.Stop();
} }
private static void Post(string url, long lTime, string body)
{
using var client = new HttpClient();
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < lTime)
{
Console.WriteLine("POST" + url + $" [{sw.ElapsedMilliseconds / 1000.0} s] " + $"[# {Thread.CurrentThread.Name}]");
var response = client.PostAsync(url, new StringContent(body));
Console.WriteLine(response.Result.StatusCode);
}
sw.Stop();
}
} }