SetProcessWorkingSetSize的实例

本文提供了一个示例代码,展示了如何使用C#和VB.NET进行内存管理,包括垃圾回收和工作集大小的设置,以减少应用程序的内存占用。
Sample Code:

//sample is probably a bad idea, but it will "trim down" the memory footprint of a .Net App (or at least the value reflected in Task Manager).

C#

   public class MemoryManagement{
        [DllImport("kernel32.dll")]
        public static extern bool SetProcessWorkingSetSize( IntPtr proc, int min, int max );

        public void FlushMemory() {
            GC.Collect() ;
            GC.WaitForPendingFinalizers() ;
            if(Environment.OSVersion.Platform == PlatformID.Win32NT) {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1) ;
            }
        }
   }

VB.NET

     Friend Sub ReleaseMemory()
      Try
           GC.Collect()
           GC.WaitForPendingFinalizers()
           If Environment.OSVersion.Platform = PlatformID.Win32NT Then
            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1)
           End If
      Catch
      End Try
     End Sub  

转自( http://www.pinvoke.net/default.aspx/kernel32.SetProcessWorkingSetSize )  

using NauraLibrary; using NauraLibrary.Logging; using System; using System.IO; using System.Runtime.InteropServices; using System.Windows; namespace DriverManagementTool { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { //强制释放进程 [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); public App() { StartLogging(); this.DispatcherUnhandledException += App_DispatcherUnhandledException; } private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Log.WriteExceptionCatch("Error", e.Exception); //MessageBox.Show(string.Format("{0}", e.Exception.Message), "Fatal error", MessageBoxButton.OK); e.Handled = true; } private static System.Threading.Mutex mutex; protected override void OnStartup(StartupEventArgs e) { mutex = new System.Threading.Mutex(true, "OnlyRun"); if (mutex.WaitOne(0, false)) { base.OnStartup(e); } else { MessageBox.Show("程序已经在运行!", "提示"); this.Shutdown(); } } public static void FlushMemory() { try { GC.Collect(); GC.WaitForPendingFinalizers(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1); } } catch (Exception ex) { Log.WriteExceptionCatch("FlushMemory", ex); } } protected static void StartLogging() { try { string logPath = NaAppSettingsReader.GetValue("LogFilePath", "./"); LogCategory fileLogCategories = NaAppSettingsReader.GetValue("FileLogSinkCategories", LogCategory.None); if (fileLogCategories != LogCategory.None) { FileLogSink localFileLogSink; string fileLogSinkDateSubDirectory = NaAppSettingsReader.GetValue("FileLogSinkDateSubDirectory", ""); if (string.IsNullOrEmpty(fileLogSinkDateSubDirectory)) { localFileLogSink = new FileLogSink(Path.Combine(logPath, "Debugger." + Environment.MachineName)); } else { localFileLogSink = new FileLogSink(logPath, fileLogSinkDateSubDirectory, "Debugger." + Environment.MachineName); } localFileLogSink.AutoFlush = true; localFileLogSink.MaxNumFiles = NaAppSettingsReader.GetValue("MaximumNumberOfLogFiles", 6); localFileLogSink.MaxDaysOld = NaAppSettingsReader.GetValue("FileLogSinkMaxDaysOld", 30); localFileLogSink.MaxFileSize = NaAppSettingsReader.GetValue<long>("MaximumLogFileSize", 1024 * 1024 * 1024); localFileLogSink.EnabledCategories = fileLogCategories; Log.Sinks.Add(localFileLogSink); } } catch (Exception ex) { Log.WriteExceptionCatch("APP", ex); } } } } 请给代码逐行加上注释解释一下
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值