'Queue work for worker threads without generating garbage
I have a method that I wish to execute on a separate thread from the main thread. It may complete and be started again at some point many times. I want to avoid generating any garbage when I want the method to run on a thread. Additionally keeping the method alive always by busy spinning is not desirable.
When using System.Threading.Tasks.Task.Run this will create a new Task object that cannot be reused, thus garbage is generated. When using ThreadPool.QueueUserWorkItem a System.Threading.QueueUserWorkItemCallbackDefaultContext object is created, thus garbage is generated. Is there any way to avoid generating garbage while also avoiding keeping the method alive when it is not needed to run?
By generating garbage I mean allocating an object on the heap every time and losing the reference to the old one so it thus becomes garbage.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
