-2

I try to improve the memory usage of VB.net WinForm application. But this code doesn't work.

<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True,CallingConvention:=CallingConvention.Cdecl)>
Public Shared Function SetProcessWorkingSetSize (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As UInt32, ByVal dwMaximumWorkingSetSize As UInt32) As Int32

End Function

I call this using this code:

  Friend Sub ReduceWorkingSet()
    Try
        GC.Collect()
        GC.WaitForPendingFinalizers()

        If Environment.OSVersion.Platform = PlatformID.Win32NT Then
            SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, UInt32.MinValue, UInt32.MinValue)
        End If
    Catch e As Exception
        Console.Out.WriteLine(e.Message)
    End Try
End Sub

I get an error which states:

Managed Debugging Assistant 'PInvokeStackImbalance' Message=Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'FXOps!FXOPS.frm__Main::SetProcessWorkingSetSize' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'

I am very new to Vb.net and don't really know how to fix the problem. I found some advice to add the CallingConvention.Cdecl to the DllImport but it didn't help. I also change the types from Long to UInt32 with not success either. It would be great if somebody can give me a hint. Thank you

  • Re "I try to improve the memory usage of VB.net WinForm application" and "I am very new to Vb.net" - I would suggest to not try to hack OS level, but learn a bit about (VB).NET memory management, garbage collection, object lifetimes, correct disposing of objects and so on. Really :) See also: https://stackoverflow.com/questions/12203969/how-to-set-minworkingset-and-maxworkingset-in-a-64-bit-net-process – Arvo Apr 20 '22 at 10:00
  • 1
    The calling convention should be `StdCall`, and the second and third args should be `UIntPtr`. The return value is a boolean also. The best solution to your problem however is not to call the function in the first place. Your reasoning that has led you to try to call the function is flawed. – David Heffernan Apr 20 '22 at 10:07

1 Answers1

-2

I suggest you consult the docs for SetProcessWorkingSetSize and read up on what the parameters are for and what are valid values.

E.g. dwMinimumWorkingSetSize "This parameter must be greater than zero [...]". You are passing UInt32.MinValue which is 0.

Hel O'Ween
  • 1,041
  • 7
  • 13