OutOfMemory Exception C # When Working With Threads

I have a service that should work forever to track a single server. To do this, I have 5 tasks that must be performed by the service (5 at the moment there will be hundreds).

I created threadpool with a maximum of 5 threads. There is a queue that threads use to get the task, then each thread processes the task, and then queues it again. The queue contains objects with 5 small attributes.

After starting the service for a while, I get an OutOfMemoryException exception in the line where I execute this:

ThreadPool.QueueUserWorkItem(currentJob.ProcessJob, (object)timeToWwait); 

timeToWwait is an int, and I no longer use it.

The context is as follows:

  ThreadPool.SetMinThreads(0, 0); ThreadPool.SetMaxThreads(5, 5); while (true) { bool processJob = false; bool checkedFrontEnd = false; _qLock.EnterWriteLock(); try { if (_jobQueue.Count > 0) { currentJob = _jobQueue.Dequeue(); // currentJob.IsActive = true; // processJob = true; } } finally { _qLock.ExitWriteLock(); } ThreadPool.QueueUserWorkItem(currentJob.ProcessJob, (object)timeToWwait); //currentJob.ProcessJob((object)timeToWwait); _qLock.EnterWriteLock(); try { _jobQueue.Enqueue(currentJob); } finally { _qLock.ExitWriteLock(); } 

Do you have any suggestions?

+4
source share
2 answers

Your problem is that you start the currentJob instance before your background task had a chance to complete. Instead, you'll want to do something like this:

  ThreadPool.QueueUserWorkItem((state) => { currentJob.ProcessJob(); _qLock.EnterWriteLock(); try { _jobQueue.Enqueue(currentJob); } finally { _qLock.ExitWriteLock(); } } ); 
+2
source

It looks like you will want to set the job again (on jobQueue) only after it is completed by the thread working on it. Imagine that there is only 1 thread and 1 job in jobQueue in the pool, if the work takes a long time, your code will execute ThreadPool.QueueUserWorkItem many times in the same job. I also think that you want to execute ThreadPool.QueueUserWorkItem if there was a job in jobQueue (from the code above it looks like it will work independently). Thanks for the interesting question.

+1
source

Source: https://habr.com/ru/post/1388548/


All Articles