I have native unmanaged dll which is static and must be loaded each time when I need library to do some work if i want to run it in parallel. In .NET I would use AppDomain and load this dll when i need it, but in NET Core AppDomains are gone (for now). I have looked at AssemblyLoadContext but there is no proper documentation with LoadUnmanagedDll. Can this be done in netstandard1.6?
Edit Currently code is called with PInvoke and is working perfectly. Problem is because nature of this unmanged dll, when I try to call it in parallel throws AccessViolationException because two or more task wants to access same memory.
If I could load dll for each time that in some context and then call PInvoke on that this problem would be gone.
One approach:
System.Runtime.Loader.AssemblyLoadContext
Load(AssemblyName assemblyName)
callingLoadFromAssemblyPath()
or returning null to fallback on default contextIntPtr LoadUnmanagedDll(string unmanagedDllName)
callingLoadUnmanagedDllFromPath()
to load your native dllinterface
Step 4 is the part you need to adjust based on the structure of the existing code. In my case, I created 3 assemblies:
In the calling code:
When instance of
nameOfTypeThatCallsPinvoke
attempts to use pinvoke method yourLoadUnmanagedDll()
override on the load context will get called.The shared interfaces are needed so types are known at compile-time. If the calling code references the pinvoke library directly it's types will differ from those obtained through the load context.
References: