WPF:将不可冻结的项目从一个Dispatcher转移到另一个Dispatcher

时间:2010-02-25 02:27:15

标签: c# wpf dispatcher

我们从XPS文档加载FixedPage对象,处理并显示它。以下代码从包中加载FixedPage:

        FixedPage fp = null;
        Package package;   // xps package
        Uri packageUri;    // uri of the package in the package store
        Uri fixedPageUri;  // uri of the fixed page
        Dispatcher _mainDispatcher // reference to the main dispatcher, passed to this function
                                   // this function runs in a different thread

        // get the fixed page stream
        Stream stream = package.GetPart(fixedPageUri).GetStream();

        // create a parser context to help XamlReader with the resources used in the page
        ParserContext pc = new ParserContext();
        pc.BaseUri = PackUriHelper.Create(packageUri, fixedPageUri);

        _mainDispatcher.BeginInvoke(
                    new UIRenderDelegate(delegate()
                    {
                        // this line takes its sweet time
                        fp = XamlReader.Load(stream, pc) as FixedPage;
                        stream.Dispose();
                    }), null).Wait();                       


        // return the created fixed page;

但是,XamlReader.Load()调用需要很长时间(特别是对于复杂的FixedPages),有时会阻止UI。我们可以使用它自己的Dispatcher在另一个线程中执行此操作,但由于FixedPage类不可解析,因此主UI线程无法使用它。

有解决方法吗?现在我们使用RenderTargetBitmap将FixedPages渲染为图像,因为BitmapSource是Freezable。

1 个答案:

答案 0 :(得分:-1)

首先将xaml加载到内存流中,然后将内存流传递给UI线程。解析UI线程上的内存流。这样你就可以在后台线程上执行慢速文件IO。只有内存解析流(使用XamlReader.Load)才能在UI线程上完成。

artice解释了如何做到这一点。

相关问题