I have Win32 application which hosts CLR runtime. No threads involved. Just main thread. And I found that on every call to managed side SynchronizationContext.Current
resets to null. I did call SynchronizationContext.SetSynchronizationContext
in class constructor which implements IDotNetEngine
. I call SynchronizationContext.SetSynchronizationContext
in Method1
but still in Method2
it will revert to null. I can set it every time but I use WinForms control from .Net side and that control uses await
when user presses keys. And because SynchronizationContext.Current
is null it will crash in code after await
because that part executed in different thread.
I found this text in SynchronizationContext.cs in source code of .Net
"The problem is that SynchronizationContexts set inside of a reverse p/invoke into an AppDomain are not persisted in that AppDomain; the next time the same thread calls into the same AppDomain, the [....] context will be null". They have solution but not for desktop .Net Framework.
So my questions is it possible to do something about it? There is no source code for that part of .Net Framewrok but it looks like .Net resets execution context (m_ExecutionContext
) when it left runtime and returns control to unmanaged code.
Details:
I use CorBindToRuntimeEx
then AppDomain.CreateInstanceFrom
and then cast ObjectHandle.Unwrap
to IDotNetEngine
interface.
IDotNetEngine declared like this:
[ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("something")]
public interface IDotNetEngine
{
void Method1();
void Method2();
}
and on unmanaged side there is similar interface.