在单独的线程上初始化组件性能



我们在创建的包含大约10个UI元素的WPF自定义控件的InitializeComponent方法上遇到了一些糟糕的性能。

此自定义控件用于在另一个STA线程中创建FixedDocument。当在创建FixedDocument之前实例化一些其他UI元素(在主UI线程上创建的页面)时,就会出现问题。

如果用户以前导航到某些页面,就会出现问题,否则一切都会好起来。

我不知道为什么会发生这种情况,但我们确信问题出在InitializeComponent方法调用上,大约需要2秒才能完成。

该应用程序的平均内存使用量约为100MB,创建FixedDocument不会占用太多内存。

以下是创建文档的代码:

private Task<string> CreateLabels()
    {
        var tcs = new TaskCompletionSource<string>();
        Thread thread = new Thread(() =>
        {
            try
            {
                FixedDocument fixedDoc = new FixedDocument();
                //Each item is a tinny ViewModel object to populate LabelView
                foreach (var item in _labelsToPrint)
                {
                    double pageWidth = 96 * 4.0;
                    double pageHeight = 96 * 2.12;
                    LabelView lv = new LabelView(item);
                    lv.Width = pageWidth;
                    lv.Height = pageHeight;
                    FixedPage fp = new FixedPage();
                    fp.Width = pageWidth;
                    fp.Height = pageHeight;
                    fp.Children.Add(lv);
                    PageContent pageContent = new PageContent();
                    pageContent.Child = fp;
                    fixedDoc.Pages.Add(pageContent);
                }
                FileInfo tempFile = new FileInfo(System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xps");
                var paginator = fixedDoc.DocumentPaginator;
                var xpsDocument = new XpsDocument(tempFile.FullName, FileAccess.Write);
                var documentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                documentWriter.Write(paginator);
                xpsDocument.Close();
                tcs.SetResult(tempFile.FullName);
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start();
        return tcs.Task;
    }

多个STA线程(主UI和我自己的)同时运行有问题吗?

谢谢你,

我想好了如何修复。我的自定义控件引用了本地化扩展(http://wpflocalizeextension.codeplex.com)。

我删除了这个引用,现在一切都很快。

不过,我不知道为什么这个扩展会引起问题。我不得不在ViewModel类上进行字符串本地化。

最新更新