MonoTouch deterministic disposing cells

2019-08-05 13:21发布

问题:

In our current app we need to perform some cleanup in the Dispose() of our custom UITableViewCells.

Unfortunately even though we call TableView.Dispose() our cells won't immediately get disposed. Instead, later on, the finalizer will call Dispose(false). Since we are called by the finalizer we shouldn't perform our cleanup here: objects might be in a unpredictable state and the time when it occurs can't be determined.

From Microsoft documentation:

The finalizer is called when the GC detects that an object is eligible for collection. This happens at some undetermined period of time after the resource is not needed anymore.

And also:

If the method is invoked from the finalizer (disposing is false), other objects should not be accessed. The reason is that objects are finalized in an unpredictable order and so they, or any of their dependencies, might already have been finalized.

Is there a solution to have the Dispose() method of our custom cells be called when the tableview is disposed?

回答1:

If you really need to call Dispose on each individual cell when Dispose is called on the table itself, you need to handle this yourself:

  1. Subclass UITableView.
  2. Store all the cells you use in a list of cells in this class.
  3. Override Dispose on the view, and call Dispose on each cell in the list.


回答2:

UITableViewCell are re-used (cached) by the UITableView. Calling Dispose on the table only removes the managed reference to the object. IOW there might still be native references to the table that will keep the cells alive longer.

It's not clear what kind of cleanup is required (that could not be done when the finalizer is executed). If it's basic UI code (i.e. your logic is elsewhere) then it should be fine (and you might be able dispose of your logic, managed-only, instances separately).