.NET Framework回收內(nèi)存操作細(xì)節(jié)披露
.NET Framework中實(shí)際上有很多應(yīng)用技巧需要我們在具體操作中去慢慢發(fā)現(xiàn),從而掌握這些提高開發(fā)效率的應(yīng)用技巧?;?NET Framework 的Windows應(yīng)用程序,你會發(fā)現(xiàn)你對程序的操作越多,占用的內(nèi)存會不斷向上飆升,即使你結(jié)束了長時(shí)間運(yùn)行的操作.這種情況對于一個(gè)非常小的應(yīng)用都是這樣.#t#
這種情況一般并不是.Net 內(nèi)存泄露,而是因?yàn)?Net沒有即時(shí)回收你分配的內(nèi)存。下面是從一個(gè)朋友那兒搞到的一段代碼,它能夠幫助你即時(shí)實(shí)現(xiàn).NET Framework回收內(nèi)存的操作.
- public class RevokeMemory
- {
- public static void ReduceMemoryFootPrint()
- {
- int currentMinWorkingSetValue = 0;
- int currentMaxWorkingSetValue = 0;
- Process currentProcess = Process.
GetCurrentProcess(); - try
- {
- if(GetProcessWorkingSetSize(current
Process.Handle, out currentMinWorking
SetValue, out currentMaxWorkingSetValue)) - {
- currentProcess.MinWorkingSet = (IntPtr)
currentMinWorkingSetValue; - }
- }
- catch(Exception err)
- {
- string additionalInfo = "MinWorkingSet
value is set to: " + currentMinWorking
SetValue.ToString(); - additionalInfo += " Process In Error:
" + currentProcess.ProcessName; - //Log error message
- }
- }
- [DllImport("kernel32.dll")]
- public static extern bool GetProcess
WorkingSetSize( IntPtr proc, out int
min, out int max ); - [DllImport("kernel32.dll")]
- public static extern bool SetProcess
WorkingSetSize( IntPtr proc, int min, int max ); - }
.NET Framework回收內(nèi)存調(diào)用的時(shí)機(jī):
1. 主界面上做一個(gè)計(jì)時(shí)器,每間隔一定的時(shí)間進(jìn)行調(diào)用,但鄙人認(rèn)為這種效果并不好。在你進(jìn)行長時(shí)間運(yùn)行的操作之前。需要禁止它。
2.每完成一個(gè)大的操作或者比較消耗內(nèi)存的操作之后,調(diào)用。
本人做了一個(gè).NET Framework回收內(nèi)存的測試,以前幾時(shí)兆的內(nèi)存飆升,現(xiàn)在總的消耗的內(nèi)存都在幾兆到30兆之間了.