开发者

'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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜