Home > Enterprise >  CoInitializeSecurity on .NET 6.0 cannot be called in time
CoInitializeSecurity on .NET 6.0 cannot be called in time

Time:08-07

I have been using the CoInitializeSecurity API function on several of my projects without any problem, but today I am facing a strange behavior that would like to share and see if someone get it working. It is a known fact that you have to use this call as earlier as possible in your project, and So I do, but the exact same code works fine in .NET 5 (or any earlier) and does not run on .NET 6, so I am out of ideas on how to fix it.

Furthermore, doing extra testing, I found out that it works fine in a ConsoleApp using .NET 6 but it does NOT when using WinForms app. Looks like in .NET 6 they changed something that is stopping this call to be successfully.

I have created a dummy repo which all the alternatives, that can be accessed here: https://github.com/creizlein/CoInitializeSecurity

I am calling the function as earlier as possible, in the form Load event or even after InitializeComponent or before, but it doesnt make any difference when using .NET 6, it works wonders on any of them using .NET 5, .NET Core 3, and old Frameworks.

Anyone knows how to get around this and get it working using .NET 6 and a WinFormsApp?

Btw, error is always the same: Security must be initialized before any interfaces are marshalled or unmarshalled. It cannot be changed once initialized.

CodePudding user response:

Simon Mourier provided the trick to the answer...

You're clearly calling it late and should call it before anything else, but I think it's more a Visual Studio 2022 issue than a .NET issue. VS 2022 loads dlls into your process: Microsoft.VisualStudio.Debugger.Runtime.NetCoreApp.dll, Microsoft.Extensions.DotNetDeltaApplier.dll, etc. if you disable Hot Reload (Project Properties / Debug) it should work (this is probably using COM to communicate between app & reloaded)


That did the trick actually, thanks a lot! I disabled Hot Reload and it started to work for .NET 6 , odd part is that it works for .NET 5 whatever you have Hot Reload or not, but I will assume thats a new feature thingy...

  • Related