Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self disposing class

Tags:

c#

invoke

dispose

I have a class that manages a process. When calling Stop() or Dispose() on this class, it will first send TCP command to the process to ask it to close itself, then check back in 1 second time, if it's not close, call CloseMainWindow(), then wait another seconds, if it's still running, call Kill().

Now I have a List<> of this class to manage a bunch of processes. When I would like to remove them from the list, I would manually call Dispose(), then Remove(). I want to make sure that I called Dispose() before I loose the only reference. Since calling Dispose() will take at least 2 second to return, it will take a while if I have say 5 items to be removed.

So I intended to have another function called SafeDispose() which Invoke() Dispose() then return. Now removing these from the list and calling SafeDispose() instead of Dispose() will be immediate while the classes itself disposing themselves slowly.

Is it advisable to do so?

like image 232
faulty Avatar asked Apr 01 '26 22:04

faulty


1 Answers

Essentially you are suggesting, leaving Dispose "as is" and instead having a helper method that tears down the object asynchronously - which is attached to the object.

Is it advisable?

Perhaps, the tricky thing about introducing threads is all the threading mess that comes with it.

  • What happens when another method accesses the object when it is asynchronously disposing?
  • What happens when another AsyncDispose is called concurrently?
  • How are errors propagated?
  • Will this introduce deadlocks?
  • Will running lots of disposes on different threads (and different objects) cause any issues? (like running out of tcp sockets)

If you can answer all in a satisfactory way then maybe.

Keep in mind you could also spin off a thread in the UI that handles all expiration and does so in a single thread (as another option)

like image 139
Sam Saffron Avatar answered Apr 03 '26 13:04

Sam Saffron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!