Reputation: 2748
I am stress testing my application and have written a simple test to spawn hundreds of threads that call a method. The code below works fine for 1000 threads and 100 ms delay.
In the code below when the number of threads is 2000 and the delay is 100 i get the error Cannot load the "shell32.dll" DLL into memory in the catch statement for radButtonEmptyThread_Click
C# Code
private void radButtonEmptyThread_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < int.Parse(radTextBoxWaitThreads.Text); i++)
{
Thread Trd = new Thread(() => EmptyThreadRequest(int.Parse(radTextBoxFloodDelay.Text), i));
Trd.IsBackground = true;
Trd.Start();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void EmptyThreadRequest(int delay, int count)
{
try
{
System.Threading.Thread.Sleep(delay);
Debug.Print(count.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
Upvotes: 1
Views: 668
Reputation: 2748
C# Code
private void radButtonCallEmptyTasks_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < int.Parse(radTextBoxWaitThreads.Text); i++)
{
// Create a task and supply a user delegate by using a lambda expression.
var taskA = new Task(() => EmptyTaskRequest(int.Parse(radTextBoxFloodDelay.Text), i));
// Start the task.
taskA.Start();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void EmptyTaskRequest(int delay, int count)
{
try
{
System.Threading.Thread.Sleep(delay);
Debug.Print(count.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
Upvotes: -1
Reputation: 631
To deal with the captured variable issue, inside the loop do this:
int x = i;
Thread Trd = new Thread(() => EmptyThreadRequest(int.Parse(radTextBoxFloodDelay.Text), x));
And of course, consider using Tasks.
2000 is a functional limit enforced by Windows. I think it might have something to do with minimum stack allocated to each thread, but I would not bet my life on it. Tasks are very light weight threads, prefer them over threads when possible.
Upvotes: 1
Reputation: 44336
Stop creating so many threads. That's very resource-intensive. Instead, use Tasks.
i
is a captured variable, which means the threads all access the original variable, not a copy. If you create a copy of the variable inside the loop, it will work as expected.
Upvotes: 2