I have a self hosted WCF service. It offers a processing function DoSth().
The processing might take long so I need to return OK to the caller prior to finish the task. Currently I've implemented that by calling
Task.Factory.StartNew(() => DoWork());
Might it be possible that the garbage collector interferes so that the just created task may never finish?
If the program is self hosted, I would say that it does not interfere as long as the host is running (static variables also remain their value). Please correct me if I'm wrong.
But how would garbage collection react if the service is hosted in IIS? If it interferes is there a way to prevent it?
Best How To :
The GC is never going to collect an object that might possibly be accessed by an executable code in the future (at least through any managed reference). That's how it is designed.
If there's any possible way for some code to execute that would use the object, then the GC isn't allowed to clean it up. It only cleans up objects that it can prove are never going to be accessed by any executable code ever again.
Since this task, the delegate it was given, and the objects used within the delegate can all be accessed by the thread that will be processing this request, they're all accessible, and are not eligible for collection.
Basically the only time you ever need to even consider the question of, "is the object I'm trying to use potentially going to end up cleaned up by the GC before I'm done with it" is when you're dealing with non-managed references, such as when using the
WeakReference class or when interoping with other languages.