Wrote a short class for use with a load test. Probably it could be useful to someone else:-)
The class basically initiates e.g. 100 threads, and through a predefined delegate some method can be called more or less simultaneously from all of the threads.
Please remember that the .NET runtime allocates 1 MB ram to each thread. Hence you will get an OutOfMemory Exception if you attempt to initialize more threads than the memory available on your client can handle (1.000 threads ~ 1GB memory).
How to use the LoadTest
class Program
{
static void DoWork()
{
Console.WriteLine("test");
}
static void Main(string[] args)
{
LoadTest load = newLoadTest(100, DoWork);
load.Start();
}
}
LoadTest Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace LoadTest
{
public delegate void TestMethod();
public class LoadTest
{
static TestMethod m_TestMethod;
static List m_ThreadWaitEvents = new List();
Int32 m_NumberOfThreads = 0;
static void baseTestMethod()
{
//Reference m_ThreadWaitEvents
AutoResetEvent threadWaitEvent = new AutoResetEvent(false);
m_ThreadWaitEvents.Add(threadWaitEvent);
threadWaitEvent.WaitOne();
//Invoke the test method
m_TestMethod.Invoke();
}
public void Start()
{
foreach (AutoResetEvent e in m_ThreadWaitEvents)
{
e.Set();
}
}
public LoadTest(Int32 numberOfThreads, TestMethod testMethod)
{
m_TestMethod = testMethod;
m_NumberOfThreads = numberOfThreads;
//Initialize threads
for (Int32 t = 0; t < m_NumberOfThreads; t++)
{
Console.WriteLine("Waiting. Thread " + t + " initiated.");
Thread thread = new Thread(baseTestMethod);
thread.Start();
}
//Wait until all threads are initialized and references threadWaitEvent
while (m_ThreadWaitEvents.Count < m_NumberOfThreads)
{
Console.WriteLine("Initializing. " + m_ThreadWaitEvents.Count.ToString() + " of " + m_NumberOfThreads.ToString() + " threads started.");
Thread.Sleep(100);
}
}
}
}