WPF:将不可冻结的项目从一个调度程序转移到另一个调度程序
我们从 XPS 文档中加载固定页面对象,处理并显示它。以下代码从包中加载固定页面:
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() 调用需要很长时间(特别是对于复杂的固定页面),有时会阻塞用户界面。我们可以在另一个线程中使用它自己的 Dispatcher 来执行此操作,但由于固定页面类不可释放,因此主 UI 线程无法使用它。
有办法解决这个问题吗?现在,我们陷入了使用 RenderTargetBitmap 将固定页面渲染为图像的困境,因为 BitmapSource 是 Freezable。
We load FixedPage objects from an XPS document, process and displays it.The following code does the loading of the FixedPage from a Package:
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;
However, that XamlReader.Load() call takes a long time (especially for complex FixedPages) and sometimes blocks the UI. We could do this in another thread with it's own Dispatcher, but since the FixedPage class is not freeazable, its can't be used by the main UI thread.
Is there a way around this? Right now we're stuck rendering the FixedPages as images using RenderTargetBitmap since BitmapSource is Freezable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先将 xaml 加载到内存流中,然后将内存流传递给 UI 线程。在 UI 线程上解析内存流。这样你就可以在后台线程上执行缓慢的文件 IO。仅流的内存解析(使用 XamlReader.Load)会在 UI 线程上完成。
这 文章解释了如何做到这一点。
Load the xaml into a memory stream first and them pass the memory stream to the UI thread. Parse the memorystream on the UI thread. This way you could do the slow file IO on he background thread. Only the inmemeory parsing of the stream (using XamlReader.Load) would be done on the UI Thread.
This artice explains how to do it.