Dispatcher xps memory leak

2019-02-21 01:35发布

问题:

I'm call a .net 4.0 dll from a vb6 app using com interop. In .net I create an xps document, via a xaml fixed document and save it to disk. This causes and memory leak and I've found a great solution here.

Saving a FixedDocument to an XPS file causes memory leak

The solution above, that worked for me, involves this line of code:

    Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.SystemIdle, new DispatcherOperationCallback(delegate { return null; }), null);

What exactly is happening with this line of code. Is that by setting the delegate to null this disposes the Dispatcher object?

回答1:

While it initially appears that the supplied code does nothing, it actually has a non-obvious side effect that is resolving your problem. Let's break it down into steps:

  • Dispatcher.CurrentDispatcher Gets the dispatcher for the current thread.
  • Invoke synchronously executes the supplied delegate on the dispatcher's thread (the current one)
  • DispatcherPriority.SystemIdle sets the execution priority
  • new DispatcherOperationCallback(delegate { return null; }) creates a delegate that does nothing
  • null is passed as an argument to the delegate

All together, this looks like it does nothing, and indeed it actually does do "nothing". The important part is that it waits until the dispatcher for the current thread has cleared any scheduled tasks that are higher priority than SystemIdle before doing the "nothing". This allows the scheduled cleanup work to happen before you return to your vb6 app.