Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad idea to write the Dispose/Close method to be asynchronous?

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?

like image 748
Ansis Māliņš Avatar asked Jun 01 '11 12:06

Ansis Māliņš


3 Answers

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.

like image 152
Lazarus Avatar answered Oct 18 '22 05:10

Lazarus


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.

like image 34
jdehaan Avatar answered Oct 18 '22 04:10

jdehaan


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.

like image 1
tster Avatar answered Oct 18 '22 04:10

tster