I need to call a method many times (ten millon), therefore I use threads. But when the loop has 100 cycles of my method, it launchs an OutOfMemoryException.
I tried add SetMaxThreads to only run 50 threads simultaneous but don’t works (because I don’t know how to do it). Thanks in advance.
ThreadPool.SetMaxThreads(50, 50);
for (int i = 0; i < tablePersons.Rows.Count; i++)
{
Thread t = new Thread(RegisterPerson);
t.Start(tablePersons.Rows[i]);
}
static void RegisterPerson(object paramObject)
{
DataRow person = (DataRow)paramObject;
Call a service...
}
Rather than creating that many separate threads manually, you should probably use Parallel.ForEach(), and let that handle the thread creation for you.
They won’t all run simultaneously, but you won’t run into memory issues.