- Home /
why does UnityWebRequest want Dispose() ?
The Unity Docs state:
Signals that this [UnityWebRequest] is no longer being used, and should clean up any resources it is using.
You must call Dispose once you have finished using a [UnityWebRequest] object, regardless of whether the request succeeded or failed.
Why doesn't UnityWebRequest rely on regular garbage collection ?
Answer by Baroque · Apr 24, 2017 at 10:44 PM
Same reason any operating-system level resource (file handles, sockets, etc.) doesn't rely on garbage collection--web requests rely on system sockets, which should be closed manually to clear up resources when you're done with them.
It's a little misleading because actually they will get garbage collected eventually, e.g. when the game stops running. You have no way of predicting when this will happen, what overhead it may add, and you have no way of handling or even detecting any errors that occur while doing so. It is a best practice to clean up after yourself.
This is typical of any garbage collected environment.
For more information microsoft has some resources over here. Also always a good source are Eric Lipperts blog posts. He talks about all the myths around garbage collection and finalizers (destructors).
Problem is: UnityWebRequest doesn't know when you don't have any references to it! That's not how a GC works. The blog post linked by @Bunny83 is especially informative.
If you want some syntactic sugar to make using Disposable objects more pleasant, the using statement will guarantee Dispose gets called after a particular clause and generates the appropriate exception handlers etc.
okay okay, i'll read the blog post, and then come back w/ my scathing counter-example. i'll call it Orion's GCd UnityWebRequest. but seriously, thanks again.