代码之家  ›  专栏  ›  技术社区  ›  Joey

.NET最小化托盘并最小化所需资源

  •  8
  • Joey  · 技术社区  · 16 年前

    我有一个WinForms应用程序(我使用的是VB),可以最小化到系统托盘。我使用了多篇文章中描述的“hackish”方法,使用NotifyIcon并播放Form_Resize事件。

    如果有人认为这个应用程序相关,这里有一个简短的描述:我有一个windows窗体,它带有一个ListView,其中包含我的it部门的工单。应用程序有一个“监听器”,在提交新工作单时发出通知。因此,当应用程序在系统托盘中运行时,我真正要做的就是每隔几分钟将ListView中的项目数与SQL表中的行数进行比较。

    4 回复  |  直到 16 年前
        1
  •  8
  •   Jesse C. Slicer    16 年前

    调用MiniMizeMemory()将进行垃圾收集,调整进程的工作大小,然后压缩进程的堆。

    public static void MinimizeMemory()
    {
        GC.Collect(GC.MaxGeneration);
        GC.WaitForPendingFinalizers();
        SetProcessWorkingSetSize(
            Process.GetCurrentProcess().Handle,
            (UIntPtr)0xFFFFFFFF,
            (UIntPtr)0xFFFFFFFF);
    
        IntPtr heap = GetProcessHeap();
    
        if (HeapLock(heap))
        {
            try
            {
                if (HeapCompact(heap, 0) == 0)
                {
                    // error condition ignored
                }
            }
            finally
            {
                HeapUnlock(heap);
            }
        }
    }
    
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool SetProcessWorkingSetSize(
        IntPtr process,
        UIntPtr minimumWorkingSetSize,
        UIntPtr maximumWorkingSetSize);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern IntPtr GetProcessHeap();
    
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool HeapLock(IntPtr heap);
    
    [DllImport("kernel32.dll")]
    internal static extern uint HeapCompact(IntPtr heap, uint flags);
    
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool HeapUnlock(IntPtr heap);
    
        2
  •  3
  •   Esteban Brenes    16 年前

    SetProcessWorkingSetSize

    但是,如果大部分内存仍然由您尚未释放的资源占用,那么最小化工作集将不会起任何作用。这与强制垃圾收集的建议相结合可能是你最好的选择。

    一些资料来源:

    .NET Applications and the Working Set

    How much memory does my .Net Application use?

        3
  •  2
  •   StingyJack    16 年前

    要清理未使用的内存,请使用GC.Collect()。。。尽管你应该仔细阅读为什么要这么做,为什么经常使用它通常是个坏主意。

    如果你是指其他资源,你需要更具体。