从未知线程收集 gc 时出现致命错误

fatal error in gc collecting from unknown thread

我在 运行 我的应用程序中使用 Microsoft-IIS/10.0,AspNetMvc-版本:5.2,AspNet-版本:4.0.30319。当我从非托管 dll(C 代码)调用函数时发生了问题。一切都适用于 3 或最多 5 运行 宁。之后 "fatal error" 发生并且应用程序停止。任何帮助都会受到欢迎。感谢和问候

如果使用非托管资源,您必须释放它们,或者如果已经释放,则不要尝试再次释放它们。一些代码在这里会有很大帮助,但听起来您在 finalize 方法或其他东西中遇到了一个空指针,然后垃圾收集器正在尝试处理引用一个空指针的对象。

例如

[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll", SetLastError=true)]
static extern IntPtr GetDC(IntPtr hWnd);
public class ExampleClass
{
   private int _hwnd;
   private IntPtr _dc;   
   public ExampleClass(int hwnd) : IDispose
   {
      this._dc = GetDC(hWnd);
      this._hwnd = hwnd;
      Console.WriteLine("Got pointer to device context of window with hWnd" + hwnd.toString());
   } 

   public void Dispose(){
      ReleaseDc(this._hwnd, this._ds);
   }

   ~ExampleClass()
   {
      Console.WriteLine("Finalizing object");
      ReleaseDc(this._hwnd, this._ds); //Bang, the handle was already released in the dispose method....
   }
}
Here is my code:

public class FmuInstance : IDisposable
{
    private readonly string fileName;
    private IntPtr wrapper;

    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("kernel32.dll")]
    public static extern IntPtr FreeLibrary(IntPtr library);


    public void LoadDLL(string path)
    {
        wrapper = LoadLibrary(path);
        if (wrapper == IntPtr.Zero)
            throw new DllNotFoundException("----");
        FreeLibrary(wrapper);
    }

    public void FreeDLL()
    {
        FreeLibrary(wrapper);
    }

    public void FreeInstance()
    {
        if (wrapper != IntPtr.Zero)
            FreeDLL();
        wrapper = IntPtr.Zero;
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // Free managed resources
            }
            // Free unmanaged resources
            FreeInstance();
            // Avoid disposing multiple times
            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}