Instead of doing the cleanup on the same thread (or launching a background thread and blocking till it completes) start the cleanup on a "background" (IsBackground = false, so it doesn't get terminated prematurely) thread and return immediately.
When is this a bad idea and how bad? Is this ever a good idea?
I think you'd want to look hard at the time to dispose of your unmanaged resource compared with that of initiating the background thread. If it's a heavily used process you could find this generating a significant overhead, if nothing else.
If the unmanaged resource is very expensive to create and destroy then perhaps you could look at maintaining a common instance or pool of instances for the life of your app.
Replacing the Dispose()
from the IDisposable
with an asynchronous cleanup violates the Liskov Subsitution Principle as one would expect the resources to be available again immediately after the call.
I suppose this is some optimization needed because of frequent allocation/deallocation, which would mean that in the end you might just shift the problem to an increasing amount of objects pending to be disposed in the background thread. That will lead to memory shortage over a longer time and need some synchronization to make sure the amount of these objects doesn't grow to the sky.
Like Lazarus said, a more adequate solution could be to have a pool of reusable objects.
One place you wouldn't want to do this is if your object to holding some limited resources that other threads might be waiting to use.
I'm very interested to see other answers, as I think this is an interesting idea, and might be a nice way in some cases to return data to the user faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With