Memory leak in WPF of Dispatcher and MediaContext objects resulting in Win32Exceptions - by Samuel Berger

Status : 

  Won't Fix<br /><br />
		Due to several factors the product team decided to focus its efforts on other items.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 648683 Comments
Status Closed Workarounds
Type Bug Repros 3
Opened 3/1/2011 2:55:59 PM
Access Restriction Public


Our web application generates a lot of images (layered building plans) through low level WPF by non-STAThreads with cached frozen objects, like Geometries, Brushes, DrawingGroups. The rendering process is parallelized trough Tasks. In .NET 4 the ThreadPool regularly terminates Threads without releasing the associated Dispatchers. 
The private static WeakReference list _dispatchers in Dispatcher class is steadily growing until exceptions occur upon creating WPF-objects:
    Exception type: System.ComponentModel.Win32Exception
    Exception message: The operation completed successfully
This occurs inside the Dispatcher -> MS.Win32.HwndWrapper constructor.
With a memory profiler we could find out, that the Dispatcher remains in memory because a reference is hold by a MediaContext object. As soon as e.g. DrawingContext.RenderOpen is called, a MediaContext object is created that will never be released. This results in steady growing memory usage and handles until the error occurs.
A similar error is bug ID 620588.
Sign in to post a comment.
Posted by Microsoft on 3/11/2011 at 10:07 AM
I think that there are a couple of issues here:
1) The memory leak because dispatchers are leaked, even when the thread dies.
2) The exception inside the HwndWrapper constructor. Each Dispatcher uses an HWND internally for messaging. I think this exception occurs because we exceed the quota for HWND handles. The Dispatcher needs to be properly shutdown to release the HWND.

The short answer: WPF objects need to be created on Dispatcher threads, not thread-pool threads. I usually recommend dedicating a thread to run the dispatcher loop to service requests to create objects and return them frozen.

The memory leak is interesting, but the scenario still won't be fixed, so we will probably not fix that issue.

-- The WPF Team
Posted by Microsoft on 3/1/2011 at 3:14 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(