System.ComponentModel.Win32Exception

Hello everything is fine?
I’m getting the following error below and we’ve been trying to identify what it is for months, but without success. Can you tell us if there is any common error in Gembox that generates this message?

Tipo Arquivo (Archive type): HTML to Tipo Arquivo (Archive type): PDF

Parametros (Parameters):

{“MargemSuperior”:20.0,“MargemInferior”:20.0,“MargemEsquerda”:20.0,“MargemDireita”:20.0,“TipoFolha”:9,“Orientacao”:0}

System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D wc_d)
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.Media.MediaContextNotificationWindow…ctor(MediaContext ownerMediaContext)
at System.Windows.Media.MediaContext…ctor(Dispatcher dispatcher)
at System.Windows.Media.MediaContext.From(Dispatcher dispatcher)
at System.Windows.Media.Visual.VerifyAPIReadWrite()
at …ctor(DrawingContext , , , )
at ​ .()
at .(Boolean )
at .()
at .()
at . ​( )
at GemBox.Document.PdfSaveOptions.67tg5rkvl9zwp8v7723mndgzuc3b4vj8 ​(DocumentModel , Stream , String )
at SC.SDK.PDF.WebAPI.Util.Converter.ConverterParaPDF(Byte documento, TipoExtensaoDocumento tipoExtensao, PropriedadesPagina propriedadesPagina) in xxxxxxx :line 63
at xxxxxx.ConverterArquivo(Byte arquivo, TipoExtensaoDocumento tipoArquivo, TipoExtensaoDocumento tipoArquivoDestino, PropriedadesPagina propriedadePagina) in xxxx :line 103

Hi Reinaldo,

What version of GemBox.Document are you using?
Please try again with the current latest version, does that solve your issue?

Regards,
Mario

We have on our solution GemBox.Document version 25.3.30.1143 and GemBox.SpreadSheet version 39.3.30

I see, note that those are old versions that have an issue with WPF Dispatcher.

You should either upgrade your licenses and use the latest versions, or use something like this:

public static class GemBoxExtensions
{
    public static void SaveSafe(this ExcelFile workbook, string path, GemBox.Spreadsheet.PdfSaveOptions options)
    {
        var thread = new Thread(() =>
        {
            workbook.Save(path, options);
            System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
        });
        thread.Start();
        thread.Join();
    }

    public static void SaveSafe(this DocumentModel document, string path, GemBox.Document.PdfSaveOptions options)
    {
        var thread = new Thread(() =>
        {
            document.Save(path, options);
            System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
        });
        thread.Start();
        thread.Join();
    }
}

I hope this helps.

Regards,
Mario

Today we have many projects connected with the old version. We try to upgrade vesion but this caused a lot of bugs on the systems. I will try the solution that you send to me and monitor how the system works. Thanks a lot for the support.

Hello,

we get a similar error:
System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D wc_d)
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.Dispatcher.get_CurrentDispatcher()
at System.Windows.Media.DrawingCollection.get_Empty()
at System.Windows.Media.DrawingGroup…cctor() — Ende der internen Ausnahmestapel berwachung —
at ? …ctor(Boolean , ? , Double )
at ? . ( ? , Boolean , Double )
at ? …ctor()
at GemBox.Document.PdfSaveOptions.67tg5rkvl9zwp8v7723mndgzuc3b4vj8 ? (DocumentModel , Stream , String )
at GemBox.Document.DocumentModel.Save(Stream stream, SaveOptions options)
at x2.Services.Pdf.Processor.Program.SaveToPdfInternal(DocumentModel documentModel, PdfConformanceLevel level, PdfReturningObject returnObject) at x2.Services.Pdf.Processor.Program.<>c__DisplayClass2_0.

We use the Gembox.Document NuGet v35.1265 which should have fixed the problem with the WPF dispatcher. In addition, we have implemented the recommended workaround using System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown as shown in your example.
Unfortunately, the above error still occurs. We believe that in our case, the above error with Gembox.Document v35.1265 occurs much more frequently.

We use Gembox.Document in an EXE to convert docx documents to PDF. This exe is restarted by a Windows service running as LocalSystem for each individual docx document and the exe is terminated after the conversion.
Start EXE, EXE converts docx to pdf, end or kill exe
again
Start EXE, EXE converts docx to pdf, end or kill exe
again …

What was fixed with regard to the WPF Dispatcher? As mentioned ee believe that in our case, the above error with Gembox.Document v35.1265 occurs much more frequently.

Just in case, can you please try again with the current latest version:

If the problem remains, can you send us a small Visual Studio project that reproduces your issue so that we can investigate it?

Hello Mario,
unfortunately the issue with NuGet package v35.0.1331 still exists.
We can’t reproduce the error on our developer machines unfortunately. The error also occurs irregularly with customers.
As already mentioned, we have integrated Gembox.Document in a .NET 4.7.1 EXE to generate a PDF from Docx. This EXE is started per document and terminated again after the PDF generation. Thus, all native Windows resources (handles) of the process should be released again after the EXE is terminated.
However, the exception indicates that no further system resources are available to generate a dispatcher when the EXE is (next) called with an error. That would mean however, Gembox occupies or uses global Windows resourcen, which are released possibly not again or not fast enough again? Is that so?
What would you recommend? Should the EXE perhaps not be started and ended per document? Would it be better for Gembox.Document regarding the dispatcher issue to start the EXE only once and then use this one instance of the EXE to convert all the docxs to PDFs?
Background info: The EXE is called by a Windows service running under the LocalSystem account, as said once per document.

Hi,

You mentioned this:

Start EXE, EXE converts docx to pdf, end or kill exe

Can you please share with us exactly how you’re executing this workflow?
We would like to recreate it and observe the GemBox behavior in that context.

Regards,
Mario

Hello Mario,
we have opened a support ticket with further descriptions and uploaded a zip file with relevant parts of our source code.
Ticket: Login - GemBox Support Center

Hi Mario,

what can we additionally try to do about the recurring System.ComponentModel.Win32Exception?

In your opinion, would switching to the .netstandard 2.0 variant of the Gembox be a possibility that could provide a remedy? System.Drawing doesn’t seem to be used there anymore and the call stack of the exception contains System.Drawing, doesn’t it?

Or should the EXE only be started if it is not already running? And not start and stop/kill it per Docx document as it is now?

Should we try to log certain performance counters when the above exception occurs? If so, which performance counters might help you with the analysis?

In some cases, we see these two exceptions in addition in the immediately after the above-mentioned System.ComponentModel.Win32Exception:

Anwendung: Services.Pdf.Processor.exe
Frameworkversion: v4.0.30319
Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet.
Ausnahmeinformationen: System.NullReferenceException
bei System.Windows.Threading.Dispatcher.ShutdownImplInSecurityContext(System.Object)
bei MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(System.Object)
bei System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
bei MS.Internal.CulturePreservingExecutionContext.Run(MS.Internal.CulturePreservingExecutionContext, System.Threading.ContextCallback, System.Object)
bei System.Windows.Threading.Dispatcher.ShutdownImpl()
bei System.Windows.Threading.Dispatcher.StartShutdownImpl()
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
bei System.Windows.Threading.Dispatcher.CriticalInvokeShutdown()
bei x2.Services.Pdf.Processor.Program+<>c__DisplayClass2_0.b__2()
bei System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
bei System.Threading.ThreadHelper.ThreadStart()

Name der fehlerhaften Anwendung: Services.Pdf.Processor.exe, Version: 1.71.8544.27323, Zeitstempel: 0x646e28f7
Name des fehlerhaften Moduls: WindowsBase.ni.dll, Version: 4.8.4614.0, Zeitstempel: 0x63996df9
Ausnahmecode: 0xc0000005
Fehleroffset: 0x0000000000139746
ID des fehlerhaften Prozesses: 0x2488
Startzeit der fehlerhaften Anwendung: 0x01d993a0ff0a1de5
Pfad der fehlerhaften Anwendung: C:\Program Files (x86)\medatixx\x2 Server\Services.Pdf.Processor.exe
Pfad des fehlerhaften Moduls: C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\WindowsBase\ca6294f2f6365f2c7d7d58e4b688ab04\WindowsBase.ni.dll
Berichtskennung: 89693622-90e3-46e7-88a7-1e7c891ffa87

Hi,

I had a similar issue with my services that use GemBox in background threads to load and handle documents of different types. After handling a large number of background tasks, the services started throwing Win32 exceptions.

However, the first Win32 exceptions had the message “System.ComponentModel.Win32Exception (0x80004005): Not enough memory resources are available to process this command.”

After a few more tasks, the thrown exception changed to the Win32 exception “System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully”.

Could there be a Dispatcher leak within GemBox that causes a resource scarcity? Or are the used dispatchers only cleared, when GemBox is not called in a new Thread?

More info:

  • I am using GemBox.Bundle in version 47.0.1072-hotfix.
  • Stacktrace for first exception:
    at MS.Win32.UnsafeNativeMethods.CreateWindowEx(Int32 dwExStyle, String lpszClassName, String lpszWindowName, Int32 style, Int32 x, Int32 y, Int32 width, Int32 height, HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, Object pvParam)
    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.Dispatcher.get_CurrentDispatcher()
    at​​ …ctor(Boolean , , Double )
    at​ .( , Boolean , Double )
    at …ctor()
    at .( )
    at GemBox.Document.DocumentModel.(PaginatorOptions , , , Boolean )
  • Invoking the dispatcher shutdown manually as Mario suggested seemed to help avoiding the exceptions

Kind regards,
Sarah

Hi,

A few months ago (in January, 2023) we refactored our handling of WPF dispatcher resource leaks when using GemBox functionalities that use WPF under the cover in a multithreaded environment.

In our new code, before GemBox uses WPF, it checks if the WPF dispatcher is already created for the currently executing thread, and if it is, then GemBox doesn’t handle it, since GemBox didn’t create it.

If the dispatcher is not created, that means that it will be created with the next WPF operation and our code creates an instance of an internal WpfDispatcherHandler class and puts it in a field decorated with a ThreadStatic attribute so that instance is associated with the currently executing thread (it is stored in a thread-local storage of the currently executing thread).

This internal WpfDispatcherHandler class also has a finalizer which gets called by the .NET runtime (garbage collector) after the thread associated with that WpfDispatcherHandler instance goes out of scope.

In this finalizer, we clear WPF dispatcher resources by using reflection to access private fields of a Dispatcher class instance by calling the Dispose method on them.

One reason for a finalizer to not be called could be if the process is explicitly killed instead of ending in a usual way (after its last instruction is executed) because finalizers might not run then.

Another reason for resources not to be released is if the process is running in a Medium Trust because then reflection over private members cannot be used.

If GemBox is unable to free WPF dispatcher resources, then the user’s code should do it as the last instruction of the currently executing thread as Mario already explained before.

WPF dispatcher resources are global to an operating system session not to process (for example, window handles) so even if a process is killed, resources are not freed automatically.

I hope this information helps!

Regards,
Stipo

Hi Stipo,

thank you for the insights! I will have a closer look at the process resources in my code.

Kind regards,
Sarah

Hi GemBox Team,

does GemBox.Document still use the WPF dispatcher?
Since cross-platform support has been added in version 35.0.1573, I thought the reference to WPF could be gone. Or is it still used for projects in Windows-only target frameworks?

Kind regards,
Sarah

Yes, it is still used in projects that target Windows (e.g. “net6.0-windows” and above).

However, in the future, we plan to provide an option with which users will be able to choose what rendering mode to use.
We already have such an option for saving to image format (see the ImageSaveOptions.RenderingMode property.
But at the moment I cannot say exactly when this option will become available in PdfSaveOptions.

Regards,
Mario

1 Like