Call BeginInvoke from the destructor

I have code in a WPF application that looks like this:

public class MyTextBox : System.Windows.Controls.TextBox, IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Dispatcher.BeginInvoke((Action) delegate { // do work on member variables on the UI thread. }); } ~MyTextBox() { Dispose(false); } } 

The dispose method never gets an explicit call, so the destructor calls it. It seems that in this case the object will be destroyed before the delegate in BeginInvoke starts working in the user interface thread. It looks like it works. What's going on here? It's safe?

+7
c # wpf dispatcher
source share
2 answers

It seems that in this case the object will be destroyed before the delegate in BeginInvoke fires in the user interface thread

Finalizer queues work in the user interface message loop. An object can complete its finalizer method before the actual delegate is called in the user interface thread, but this does not matter since the delegate receives a queue in the queue.

What's going on here?

You start work with the user interface from the finalizer.

It's safe?

Safe is a broad term. Would I do it? Absolutely not. It seems odd that you are invoking manipulation of the user interface elements from the finalizer, especially considering that it is a TextBox control. I suggest you fully understand that the finalizer works and does not guarantee. Firstly, starting the finalizer does not mean that the object is immediately cleared in memory.

I also suggest reading @EricLippert posts: why is everything you know wrong, Part1 and Part 2

+4
source share

When you call BeginInvoke , you add a delegate to the queue in the dispatcher, and that delegate will point to an object that refers to the object to which Dispose was called. Since there is a reference to an object accessible through the root variable, this object is not suitable for collection.

Now this will be very confusing for others using this code, so you should try to avoid "reanimating" objects that have already been finalized, if at all possible.

+3
source share

All Articles