{"record":{"id":"762f4bc8637a9c96","repo":"dotnet/wpf","slug":"sr-format-sr-oleservicescontext-oleinitializefailure-hr","errorCode":null,"errorMessage":"SR.Format(SR.OleServicesContext_oleInitializeFailure, hr)","messagePattern":"SR\\.Format\\(SR\\.OleServicesContext_oleInitializeFailure, hr\\)","errorType":"exception","errorClass":"SystemException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/OleServicesContext.cs","lineNumber":152,"sourceCode":"    ///  Initialize OleServicesContext that will call Ole initialize for ole services(DragDrop and Clipboard)\n    ///  and add the disposed event handler of Dispatcher to clean up resources and uninitalize Ole.\n    /// </summary>\n    private void SetDispatcherThread()\n    {\n        int hr;\n\n        if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)\n        {\n            throw new ThreadStateException(SR.OleServicesContext_ThreadMustBeSTA);\n        }\n\n        // Initialize Ole services.\n        // Balanced with OleUninitialize call in OnDispatcherShutdown.\n        hr = OleInitialize();\n\n        if (!NativeMethods.Succeeded(hr))\n        {\n            throw new SystemException(SR.Format(SR.OleServicesContext_oleInitializeFailure, hr));\n        }\n\n        // Add Dispatcher.Shutdown event handler. \n        // We will call ole Uninitialize and clean up the resource when UIContext is terminated.\n        Dispatcher.CurrentDispatcher.ShutdownFinished += new EventHandler(OnDispatcherShutdown);\n    }\n\n    /// <summary>\n    ///  This is a callback when the <see cref=\"Dispatcher\"/> is shut down.\n    /// </summary>\n    /// <remarks>\n    ///  <para>\n    ///   This method must be called before shutting down the application on the dispatcher thread. It must be called\n    ///   by the same thread running the dispatcher and the thread must have its ApartmentState property set to\n    ///   <see cref=\"ApartmentState.STA\"/>.\n    ///  </para>\n    /// </remarks>\n    private void OnDispatcherShutdown(object sender, EventArgs args)","sourceCodeStart":134,"sourceCodeEnd":170,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/OleServicesContext.cs#L134-L170","documentation":"After the STA check, SetDispatcherThread calls the Win32 OleInitialize API to start COM/OLE services on the thread. If OleInitialize returns a failure HRESULT (e.g. RPC_E_CHANGED_MODE or E_OUTOFMEMORY), a SystemException containing the hr is thrown.","triggerScenarios":"OleInitialize returning S_FALSE-treated-as-failure hr such as RPC_E_CHANGED_MODE when the thread apartment was changed concurrently, or out-of-memory conditions during COM initialization, immediately after the STA check passes.","commonSituations":"Mixed-mode COM hosting where another component called CoInitializeEx with COINIT_MULTITHREADED on the same thread; COM already initialized differently by a host application (e.g. Office add-ins, COM-shimmed plugins); resource exhaustion on loaded systems.","solutions":["Ensure the thread is not previously CoInitializeEx'd in MTA mode; keep apartment mode consistent (STA) for the whole thread lifetime.","Inspect the HRESULT in the message (hr) and address the root COM issue (RPC_E_CHANGED_MODE means an apartment-mode conflict).","Move WPF initialization to a fresh, dedicated STA thread that has no prior COM initialization.","If embedding WPF in a native host, initialize COM as STA (CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)) before loading PresentationCore."],"exampleFix":"// before (host code)\nCoInitializeEx(NULL, COINIT_MULTITHREADED); // conflicts with WPF OLE init\nCreateWpfUi();\n\n// after\nCoInitializeEx(NULL, COINIT_APARTMENTTHREADED);\nCreateWpfUi();","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { InitializeWpfOleServices(); }\ncatch (SystemException ex) when (ex.Message.Contains(\"hr\"))\n{\n    // log HRESULT, fall back to non-OLE code path or restart on a clean STA thread\n}","preventionTips":["Initialize COM STA once per thread and never mix COINIT flags.","Create WPF UI on fresh threads without prior CoInitializeEx calls.","Check host application COM initialization when embedding WPF."],"tags":["wpf","com-interop","ole","hresult"],"backgroundTag":"module-init-failed","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}