I have a application which loads of messages need to be handled (e.g: 2000 per second). And the business requirement requires me not to handle the message immediately , but to wait for 2 seconds to handle every single message. what I'm doing now is to spin off a thread from thread pool via Task.Factory.StartNew for every message, and do the "waiting 2 seconds" job inside the thread from the pool. The problem is when the message load is really high, I always get OutOfMemory exception , although the memory consumption is not actually that high according to Task Manager from Windows OS. However if I don't wait inside the thread, then everything is ok.
My guess is that when the message load is high, the thread pool threads are not enough to handle all the messages. thus more and more messages are queued to wait to be handled, when the queue size gets really big, it results in a OOM exception . Have already tried ThreadPool.SetMaxThreads and ThreadPool.SetMinThreads to very high number, but still doesn't work. Any advices?
The code looks like this :
ThreadPool.SetMaxThreads(32768, 32768);
ThreadPool.SetMinThreads(2500, 2500);
public void HanldeMessage(string message)
{
Task.Factory.StartNew(() => DoWork(message))
}
public void DoWork(string message)
{
Thread.Sleep(2000);
// do some work to message
}