【发布时间】:2015-03-05 10:28:24
【问题描述】:
我正在使用 c#.net 开发一个 winform 应用程序。我的 winform 应用程序正在使用以下组件 1)Win 32 dll (使用 System.Runtime.InteropServices) 2)定时器(3个)(System.Timers) 3)Excel互操作
应用程序的内存根本没有减少。由于计时器连续运行,所以我无法处理 所以想实现 dispose 模式。
除了 Excel 互操作之外,是否有必要处理 win32 API。? 如有必要,您能否建议调用和处理 win32 API 的最佳方式。 下面列出了应用程序中使用的一些 Win32 API。
DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int netConnection, int val);
[DllImport("Oleacc.dll")]
private static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint dwObjectID, byte[] riid, ref Excel.Window ptr);
[DllImport("WtsApi32.dll")]
private static extern bool WTSRegisterSessionNotification(IntPtr hWnd, [MarshalAs(UnmanagedType.U4)]int dwFlags);
[DllImport("WtsApi32.dll")]
private static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);
【问题讨论】:
-
这些只是声明。如果你在泄漏,它在其他一些代码中。你做一个小复制怎么样?
-
你能用伪代码描述你在问什么吗?
-
@andlabs :下面是示例代码
[DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] private static extern IntPtr GetForegroundWindow();public class WinAPI { public void GetActiveWindowHandle { IntPtr handle = IntPtr.Zero; handle = GetForegroundWindow(); } }在上面的类中,我使用了 GetForegroundWindow() API。我正在使用它,但没有释放它的内存。您能否建议如何处理应用程序中使用的 WInAPI。 -
对于
GetForegroundWindow()和GetActiveWindow(),什么都没有。这些函数返回已经存在的资源的句柄(在前者的情况下,甚至可能不是你的窗口)。您不必(实际上也不应该)明确地释放它们。如果你有一个类可以让你创建一个窗口(也就是说,它包装了CreateWindow()或任何其他CreateXxx()函数),那么你会想要一个Dispose()调用等效的DestroyXxx()、ReleaseXxx()或CloseXxx()函数如果您自己忘记这样做(尽管这可能是一个错误)。
标签: c# winforms winapi memory-management