Multithreaded load testing C#

Multithreaded load testing C#







private static async Task LoadTest()
{
System.Net.ServicePointManager.DefaultConnectionLimit = 200;// IMPORTANT!!!

double threads = 16;
int requestsNumber = 800;

List<string> links = new List<string>();

for (int i = 0; i < requestsNumber; i++)
{
links.Add("http://localhost");
}

int workingThreads = 0;

ManualResetEvent startEvent = new ManualResetEvent(false);
ManualResetEvent finishedEvent = new ManualResetEvent(false);

int requestsPerThreadNumber = (int)Math.Ceiling(links.Count / threads);

Console.WriteLine("Creating threads");
var results = new List<List<long>>();
for (int i = 0; i < threads; i++)
{
var requestsPerThread = links
.Skip(i * requestsPerThreadNumber)
.Take(requestsPerThreadNumber)
.ToList();

List<long> res = new List<long>();
results.Add(res);

Action<object> action = p =>
{
Stopwatch sw = new Stopwatch();

sw.Start();

// prepared signal
Interlocked.Increment(ref workingThreads);

startEvent.WaitOne();

List<string> requests = (List<string>)p;

// test
try
{
foreach (var request in requests)
{
// do work here
// Do();

res.Add(sw.ElapsedMilliseconds);
sw.Restart();
}
}
catch { }
finally
{
if (Interlocked.Decrement(ref workingThreads) == 0)
{
finishedEvent.Set();
}
}
};

Thread t = new Thread(new ParameterizedThreadStart(action));
t.Name = "thread " + (i + 1);

t.Start(requestsPerThread);
}

while (workingThreads < threads)
{
Thread.Sleep(1000);
}

startEvent.Set();

Stopwatch total = new Stopwatch();
total.Start();

finishedEvent.WaitOne();

long totalElapsed = total.ElapsedMilliseconds;

var all = results.SelectMany(s => s.Select(x => x)).ToList();

var avg = all.Average();

Console.WriteLine("Success: {0}; Avg: {1}; TotalTime: {2}; Threads: {3};", all.Count, avg, totalElapsed, threads);
}

No Comments

Add a Comment