关于Mobile系统内存不足而崩溃的总结.docx
《关于Mobile系统内存不足而崩溃的总结.docx》由会员分享,可在线阅读,更多相关《关于Mobile系统内存不足而崩溃的总结.docx(20页珍藏版)》请在冰豆网上搜索。
关于Mobile系统内存不足而崩溃的总结
关于Mobile系统内存不足而崩溃的调研与总结
bySkyfrog2011/9/15
异常代码:
0xc0000005
异常地址:
0x78801950
读取:
0x00000040
/Exception:
OutOfMemoryException
1.Mobile开发语言
强烈推荐C++;C#虽然简单上手快,不过实在太慢了,ARM11才做考虑,ARM9不推荐使用..........等到项目做大的时候,才发现运行速度慢想再换工具,那就非常麻烦了............(
ChoosingaProgrammingLanguageforWindowsMobileDevelopment
VisualC++
TheadvantagesofusingVisualC++areexecutionspeed,applicationsizeandflexibility.ApplicationswritteninC++runveryquicklyandconsumeminimalresources:
fast-actiongamesaregoodexamplesofprogramsthatbenefitfromC++.Furthermore,theabilitytoaccesslow-levelsystemcomponentsmeansthatusingC++istheonlywaytocreateaTodayorHomescreenplug-in.
VisualC++applicationscaninteractwiththeWindowsMobilepowereddevicebycallingtheWin32APIs(ApplicationProgramInterfacefunctions).TheseAPIsarefunctionsthatperformparticularactions,suchasplayingasoundordrawingabuttononthescreen.TherearethousandsoftheseAPIs(WindowsMobilesupportsasubsetofthecomplete"desktop"WindowssetofWin32APIs),andtheyaredocumentedinthesectionentitledWindowsMobileFeatures(Native).Whenbrowsingthissection,payparticularattentiontothefactthatsomeAPIsareavailableonlyinWindowsEmbeddedCE-aplatformthatisrelatedto,butseparatefrom,WindowsMobile.AtableinthetoprightofeachtopicwillclarifywhichAPIissupportedbywhichplatform.
IfyouhaveexperiencedevelopingforWindowsusingVisualC++,youwillnotfindthetransitiontoWindowsMobileparticularlyjarring.Youshouldreadthesectionscoveringinstallingandusingthetools,andthenthetopicMakinguseofDevice-SpecificFeaturesMwhichwillhighlighttheuniqueabilitiesofWindowsMobilepowereddevices.
IfyouarenewtobothprogrammingandWindowsMobile,itmaybeagoodideatobeginwithVisualC#,andthentransitiontoVisualC++.
VisualC#andVisualBasic
VisualC#andVisualBasic.NETare"managed"developmentlanguages.Notonlyaretheyrelativelyeasytolearn,buttheysupportthe.NETCompactFramework-alibraryofclassesthatperformalotoffrequentlyusedprogrammingtasks,togreatlysimplifyapplicationdevelopment.
ThedevelopmenttoolsforC#andVisualBasic.NETincludeafullywhat-you-see-is-what-you-getuserinterfacedesigner.Youcandraganddropbuttonsandothercontrolsdirectlyontoyourapplication'swindow(calleda"form"inmanagedprogramming),andthendouble-clicktoaccesstheunderlyingcode.Thisapproachmakescreatinganapplication'suserinterfaceextremelyfastandeasy.
ExtraclassescoveringeverythingfromdatastructurestointerceptingtextmessagesareavailabletoyouaspartoftheCompactFrameworklibrary.Youcanreadmoreabouttheframeworkinthesectionentitledthe.NETCompactFrameworkReference.TomakeuseofWindowsMobilespecificfeatures,asetofextraclassesareprovided.Theseprovideaccesstothedevice'sfeatures,forexample,thelistofContacts,orbuilt-incamera.ThedocumentationfortheseclassesisinthesectionentitledWindowsMobileFeatures(Managed).
TheCompactFrameworkisasubsetofthe.NETFramework,sosomefunctionalitymayrequireaslightreworkingofyourcode.
VisualC#isagreatwaytolearnprogramming.(
2.内存资源释放
(
NETCF:
Memoryleak...nowwhat?
?
20Feb20087:
12PM
Subtitles:
-OutOfMemoryException(OOM)
-SqlCeException:
Notenoughmemorytocompletethisoperation
-...
I'maSupportEngineeratMicrosoftCSS("CustomerServiceandSupport"),andIprettyoftenhandlerequestsrelatedtoNETCFapplicationscrashingwithOOMmessages,orunderaheavymemorypressureandthereforeperformingbad.IcollectedsomehintsandtechniquesISVApplicationDevelopersmayusetopreventortroubleshootit,sothatIcanpointnextdeveloperstothembyusingalinkandnotcopying\pastingeverytimethesameinitialmail...:
-)[whichfranklybtwaddresseshalfoftherequestsrelatedtoleaks...]Happyreading!
GENERICSUGGESTIONS
It’squitedifficulttogetacomprehensivesetofactionsinordertodebugamemoryleak,asit’sdependentonthespecificscenarioyou’rerunning.So,someofthefollowingsuggestioncouldbeusefulinyourcase,someotherscouldn’t.AccordinglytoThreeCommonCausesofMemoryLeaksinManagedApplicationsthe3mostcommoncausesare:
1.unmanagedresourcesnotcorrectlycleanedup
2.drawingresourcesnotcorrectly.Dispose-d
3.stillreferencedmanagedobjects
Regarding
(1),ifyou'redevelopingcustomcontrolsthenremembertoimplementFinalize&Dispose,asrecommendedbyImplementingFinalizeandDisposetoCleanUpUnmanagedResources.
Regarding
(2),considerthefollowingsubtlethingsyoushouldknow:
drawingNETCFclassessuchasFont,Image,Bitmap,Pen,Brush,etcaretinywrappersaroundthenativeresources,whicharehandledinWindowsCEbytheGWES(Graphics,WindowingandEventSubsystem).ThissimplymeansthatinNETCFapplications,whenyouinstantiatesuchclassesyoumustinvoke.Disposeontheobject,otherwisealeakwillbeproduced.ThisisthesameforMODALforms(myForm.ShowDialog)asIpointedabove:
call.Dispose()fromthemethodshowingthedialog.
Notethat,becauseofabugaddressedinv3.5,callingDispose()onanImageListobjectcausesamemoryleak.Therefore,ifyou’reusinganImageList,donotcallDispose()onit,unlessyou'reapplicationistargeting3.5.Inanycaseyoumustclearthelistifyou’vefinishedwithit:
frm.ImageList1.Images.Clear();
//NOTNEEDEDfrm.ImageList1.Images[0].Dispose();
//NOTNEEDEDfrm.ImageList1.Images[].Dispose();
//DONOTfrm.ImageList1.Dispose();
//becauseitleaksinNETCFv2–addressedinv3.5
ThesameappliestoToolbars,becausetheyhavea.ImageListproperty.Whenyouclosetheformandfreeuptheimages,don’tcall.Disposeonthe.ImageListpropertyofthetoolbar,butsimply
frm.ToolBar1.ImageList.Images.Clear()
Regarding(3),youcanleverageonsomemonitoring-tools(below)andyoushouldbeawareofsomecaveats,someofwhicharedescribedinHowto:
ImprovePerformance(.NETFrameworkDeveloper'sGuide).Soforexample:
∙SinceStringobjectsareimmutablein.NET,everytimeyoumodifythevalueofaStringinternallyanewStringobjectiscreated.UseStringBuilderinsteadofconcatenating(“+”)Stringobjects,becauseotherwisetoomuchgarbagewillbecreatedandtheGCwillkicktoooften,thusaffectingthewholeperformancesoftheapplication.
∙Avoid"NEW"statementsinloops
∙LimitthenumberofopenSqlCeCommandobjectsanddisposeofthemwhenfinished
∙...
TAKESOMETIMEtoreadthroughthatarticle...
Stillabout(3),rememberthatifyouaddaneventhandlertoacontrolthathasbeendynamicallycreated,beforedisposingthecontrolyouneedtoexplicitlyremovethateventhandler-otherwiseareferencewillbeholdforthatcontrolanditwon’tbeeffectivelygarbage-collected.
GCisveryexpensive,asitneedsto"freeze"allapplication'sthreadstorun.
NETCFANDVIRTUALMEMORY:
Ifyou'veneverlookedathowthememorylookslikeonWindowsCE-basedplatforms,youmaystartfromthis2-partblogpost:
SlayingtheVirtualMemoryMonster[DumpMemexplained]-1stpart
SlayingtheVirtualMemoryMonster[DumpMemexplained]-2ndpart
Iwon'tenteronthedetailsdescribedinthatblog,soletmewritedownsomeprobablyusefulnotes:
1-TheDLLsrelatedtotheNETCFloadedintheapplication'saddressspace(aka"processslot")areonlytheonesfortheCLR(netcfagl*andmscoree*,incasethey’renotXIPDLLsalreadyinROM,thusmeaningthey'reloadedatslot1):
alltheothermanagedassembliesareloadedintotheLargeMemoryArea(1GB\2GBinthevirtualaddressspace).Therefore,theonlyimpactmanagedmoduleshaveintheapplication’saddressspaceistheJITedcode.Thisiswhy"unloadingassembly",evenifitwaspossible,doesn'tgiveanybenefit.ThisisdocumentedbyDeviceMemoryManagement(.NETFrameworkDeveloper'sGuide)andbyMikeZintel’sblog(hewastheProgramManagerforNETCFProductGroup).NetCompactFrameworkAdvancedMemoryManagement
2-Thecode+stack+heapcanbeallocatedABOVEthe“DLLLoadPoint”:
thisisNOTaproblem.TheycanoverseethatlineandcanevenfillblankspacesbetweenseparateloadedDLLs.AnOOMmayhappenif:
*aNEWlibraryisloaded(i.e.alibrarythatwasn’tloadedbyanyotherprocesssofar,thusmeaningthattheDLLwon'tfindanyavailablespacedownwards)
*there’snomoreroomforloadingcode+stack+heapevenintheblankspacesamongtheloadedDLLs(virtualmemoryiscompletelyfull,consideringalsofragmentation)
3-COSTs:
onlymscoree*_0.dllandnetcfagl*_0.dllareloadedintoamanagedapplication’svirtualmemoryaddressspace(incasethey’renotXIPDLLsalreadyinROM),andthisistheonlyfixedcostofamanagedapplication(roughly750KB).Dynamiccostsmightbe:
*CLRDatastructures:
~250KB
*JITHeap:
~500KB(rememberabout“CodePitching”,i.e.theabilitytothrowawaytheJIT-edcodeincaseofscarcememory)
*foreachthread:
aminimumof64KB-stack(andaNON-multithreadedmanagedapplicationhas2or3threads)
*GCHeap:
~2MB,evenifaGarbageCollectiontakesplaceevery1MBofmanagedobjectsallocated(moreover,notethatwhenallocatinganobject,aVirtualAllocisinvokedforatleasta64KB-segment
*thereareotherheaps(AppDomain,Process,Short-Term),inanycasewhatRPMcalls“Totalsizeofobjects”isthetotalofallofthem.
Apartfromthecostassociatedto“pure”managed