简体   繁体   中英

'System.OutOfMemoryException' when using Font from local system cache

I have a silverlight slideshow type application ,having number of slides to display text. Each slides may have a number of TextBlock . We have requirement of Creating each TextBlock at runtime add in different panels.For each TextBlock we are assigning the value of TextBlock.Fontsource = new Fontsource(stream) .This 'stream' data is of ARIALUNI.TTF(22 MB) font which is downloaded by application in system local cache ,we read its content and assign it to TextBlock. After some slides ,it gives this exception

'System.OutOfMemoryException' at System.Windows.Documents.FontSource.SetTextFontSourceFromStream(DependencyObject obj) at System.Windows.Controls.TextBox.UpdateFontSource(FontSource fontSource) at System.Windows.Controls.TextBox.set_FontSource(FontSource value) at TestSlideControl.ShowData()

Thanks in Advance, DNM

No wonder you get an OutOfMemoryException . AFAIK Isolated Storage size defaults to a maximum of 1MB. You can either prompt the user to increase that value ( IncreaseQuotaTo() ) or use a smaller font (preferrable).

Edit : In regards to the comment.

I have noticed in the original post that you are doing TextBlock.Fontsource = new Fontsource(stream) for each TextBlock !
Which means it's ~22MB for each TextBlock you create. So for 100 TextBlocks, you get 2.2GB of memory consumed.
You should cache the variable AND somehow use a smaller font. You could make it a static property that gets created only on the first use (or if you use it every time, simply a static property initialized by constructor):

public static class FontCache
{
    public static FontSource MyCoolFontSource { get; set; }

    static FontCache()
    {
        using (Stream fontStream = ...)
        {
            FontCache.MyCoolFontSource = new FontSource(fontStream);
        }
    }
}

and in code:

TextBlock.Fontsource = FontCache.MyCoolFontSource;

Also note that you should really stream the font from either isolated storage , or from Application.GetResourceStream .

If each TextBlock you're generating uses the same font, you should assign each of them a Style . The style can establish the font you want to use as well as any other common properties you'd like to share.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM