DllImport and ASP.NET

I am having some problems with DllImport and ASP.NET because when I use the imported method, ASP.NET loads the Dll and locks the file even after it finishes. Is there a way to get ASP.NET to release a file lock?

+3
source share
3 answers

The only way to force the DLL to exit the process in .Net is to unload the AppDomain into which the Dll is loaded. If you do not create a separate AppDomain that runs the DllImport code, this will not be possible.

I also know that this policy applies to managed DLLs. I am not 100% sure if this applies to a DLL loaded via PINvoke, but I am sure.

+2

AppDomain dll . AppDomain, DLL .

+2

AppDomain - . LoadLibrary FreeLibrary pinvoke, . , FreeLibrary, , .

, , :

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);

class LibraryHandle
{
    readonly string libName;
    int refCount = 0;
    IntPtr handle;

    public LibraryHandle(string name)
    {
        libName = name;
    }

    public void Increment()
    {
        if (refCount == 0)
        {
            handle = LoadLibrary(libName);
            if (Handle == IntPtr.Zero)
            {
                int error = Marshal.GetLastWin32Error();
                throw new Exception(string.Format("{0})", error));
            }
        }
        ++refCount;
    }

    public void Decrement()
    {
        if (refCount <= 0)
            return;

        if (--refCount)
        {
            // It might be better in some cases to:
            // while(FreeLibrary(handle));
            FreeLibrary(handle);
            FreeLibrary(handle);
        }
    }
}

, , ASP.NET, .

In addition, since this may violate some assumptions made by the runtime, using FreeLibrarya library that you did not load may not be a good idea.

Another alternative would be to perform any operation in a new one AppDomain, and then unload it when you are done.

0
source

Source: https://habr.com/ru/post/1706044/


All Articles