在我们的应用程序中,我们使用 PngBitmapEncoder 在单独的线程\任务中编码和保存 PNG 图像。运行应用程序几天后,我们看到 Dispatcher 无法从编码器创建并抛出错误
没有足够的存储空间来处理命令
并具有以下调用堆栈
System.ComponentModel.Win32Exception (0x80004005): Not enough storage is available to process this command
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Threading.Dispatcher..ctor()
at System.Windows.Threading.DispatcherObject..ctor()
at System.Windows.Media.Imaging.BitmapEncoder..ctor(Boolean isBuiltIn)
由于 .Net 是开源的,所以很好奇 Dispatcher 构造函数中的哪一行抛出了错误
[SecurityCritical, SecurityTreatAsSafe]
private Dispatcher()
{
_queue = new PriorityQueue<DispatcherOperation>();
_tlsDispatcher = this; // use TLS for ownership only
_dispatcherThread = Thread.CurrentThread;
// Add ourselves to the map of dispatchers to threads.
lock(_globalLock)
{
_dispatchers.Add(new WeakReference(this));
}
_unhandledExceptionEventArgs = new DispatcherUnhandledExceptionEventArgs(this);
_exceptionFilterEventArgs = new DispatcherUnhandledExceptionFilterEventArgs(this);
_defaultDispatcherSynchronizationContext = new DispatcherSynchronizationContext(this);
// Create the message-only window we use to receive messages
// that tell us to process the queue.
MessageOnlyHwndWrapper window = new MessageOnlyHwndWrapper();
_window = new SecurityCriticalData<MessageOnlyHwndWrapper>( window );
_hook = new HwndWrapperHook(WndProcHook);
_window.Value.AddHook(_hook);
// DDVSO:447590
// Verify that the accessibility switches are set prior to any major UI code running.
AccessibilitySwitches.VerifySwitches(this);
}
更新
更新了 .net 开源的构造函数代码。dispatcher.cs 可在此处获得https://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Threading/Dispatcher.cs,078d6b27d9837a35
经过一番调查,我们发现问题发生在大约 15000 次迭代后(每次迭代都会创建一个新线程并调用 PngBitmapEncoder)。然后发现这与 Global Atom Table 限制(0x4000 或 16384)有关。此处有关全局原子表的更多详细信息https://docs.microsoft.com/en-us/archive/blogs/ntdebugging/identifying-global-atom-table-leaks
每次创建的调度程序都会在全局原子表中创建一个条目,并且在线程退出时,该条目不会被清除。这会导致全局原子表中的泄漏,当它达到最大限制时,它会抛出“存储空间不足......”错误。这似乎是 Microsoft 处理 Dispatcher 的问题。即使是 PngBitmapEncoder 文档,我也没有看到任何关于 Dispatcher 处理和任何显式关闭 Dispatcher 的评论。