我的应用程序 (migradoc) 中有一个 PDF 导出。为了避免冻结 GUI,我想将此导出作为单独的线程运行。PDF 还嵌入了图表。为了使这些图表看起来像我在应用程序中使用的图表,我在代码中创建和呈现它们。(visifire) 我的线程已经是 STA,但是在运行 WPF 渲染命令时出现异常:
调用线程无法访问此对象,因为不同的线程拥有它
我的代码:
chart.Measure(new Size(311, 180));
chart.Arrange(new Rect(0, 0, 311, 180));
chart.UpdateLayout();
ExportToPng(new Uri("C:\\" + i + "c.png"), chart);
public void ExportToPng(Uri path, Chart surface)
{
if (path == null) return;
// Save current canvas transform
Transform transform = surface.LayoutTransform;
// reset current transform (in case it is scaled or rotated)
surface.LayoutTransform = null;
// Create a render bitmap and push the surface to it
var renderBitmap =
new RenderTargetBitmap(
(int) surface.Width,
(int) surface.Height,
96d,
96d,
PixelFormats.Pbgra32);
renderBitmap.Render(surface);
// Create a file stream for saving image
using (var outStream = new FileStream(path.LocalPath, FileMode.Create))
{
// Use png encoder for our data
var encoder = new PngBitmapEncoder();
// push the rendered bitmap to it
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// save the data to the stream
encoder.Save(outStream);
}
// Restore previously saved layout
surface.LayoutTransform = transform;
}
我已经尝试发送此命令,但我仍然不断收到相同的错误。
DispatcherHelper.UIDispatcher.BeginInvoke((Action)(() =>
{
chart.Measure(new Size(311, 180));
chart.Arrange(new Rect(0, 0, 311, 180));
chart.UpdateLayout();
ExportToPng(new Uri("C:\\" + i + "c.png"), chart);
}));