简体   繁体   中英

What happens to Dispatcher.Invoke if the method to be invoked gets garbage collected?

I have code like this:

var myTimer = new Timer(500);
myTimer.Elapsed += (o, a) =>
{
    Application.Current.Dispatcher.Invoke(() =>
    {
        // Handle elapsed
    }, DispatcherPriority.Render);
};

If the timer elapses and adds the anonymous method to the Dispatcher, then immediately goes out of scope and gets garbage collected before the dispatcher invokes the anonymous method, what will happen?

It's lifetime won't end specifically because the message loop is referencing it.

Even though the object is no longer in scope in code, that object is accessible through a rooted object, so the GC cannot collect it.

The whole point of using managed memory is that you can rely on the GC to only ever reclaim any managed resourced when it is impossible for them to be accessed from executable code . If it's possible for executable code to access an object, then that object will not be collected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM