c# - How to dispose of a PrivateFontCollection correctly? -
i'm using privatefontcollection install uploaded fonts on web server. code below works, on second upload of font privatefontcollection references first font uploaded. isn't being disposed of correctly. spot i'm doing wrong?
var fontname = string.empty; using (var ms = new memorystream(fontbytes)) { // used store our font , make available in our app using (var pfc = new privatefontcollection()) { //create memory pointer intptr data = marshal.alloccotaskmem((int)ms.length); try { //copy bytes unsafe memory block marshal.copy(fontbytes, 0, data, (int)ms.length); // have register font system (weird .net bug !) uint cfonts = 0; addfontmemresourceex(data, (uint)fontbytes.length, intptr.zero, ref cfonts); //pass font font collection pfc.addmemoryfont(data, (int)ms.length); var fontwithmime = "data:application/x-font-truetype;charset=utf-8;base64," + cleanfontdata; fontname = pfc.families[0].name; //db work here } { ms.close(); marshal.freecotaskmem(data); } } }
privatefontcollection flawed class , have extremely careful using it. gross bug in existing code marshal.freecotaskmem() call. ensure not call function until after code stops using any font object created family. failure causes random glyph corruption, accessviolationexception if lucky. underlying problem font continue use memory allocated alloccotaskmem(), unaware memory no longer valid. corruption occurs when memory re-used.
furthermore, while class has addmemoryfont() method, not have corresponding removememoryfont() method. way clean calling privatefontcollection.dispose(). deletes all of fonts in collection. same stipulation in previous paragraph, can call dispose() when sure no longer use font object. calling not cause exception.
very awkward behavior, safe way use pfc keep around life of app. pretty painful in web app of course.
you can assume added font last one in fontfamily[] array. not first 1 have implemented now.
Comments
Post a Comment