尤里卡。我在线程池线程中创建我的对象,这在使用 WPF 时显然是一个禁忌。相反,所有对象都需要从调度程序线程中创建。顺便说一句,这也清除了我没有发现的可怕的内存泄漏。
我原来的类定义是这样的:
public class Compositor
{
private int _width;
private int _height;
private DrawingVisual _drawingVisual;
private DrawingContext _drawingContext;
private bool _isReady = false;
public void Reset(int width, int height)
{
_width = width;
_height = height;
_drawingVisual = new DrawingVisual();
_drawingContext = _drawingVisual.RenderOpen();
_isReady = true;
}
// ... compositing methods below
}
为了纠正,我让我的类继承自DispatcherObject
,然后使用该Dispatcher
属性来实例化我的对象。
public class Compositor : DispatcherObject
{
private int _width;
private int _height;
private DrawingVisual _drawingVisual;
private DrawingContext _drawingContext;
private bool _isReady = false;
public void Reset(int width, int height)
{
Dispatcher.Invoke(
new Action(
() =>
{
_width = width;
_height = height;
_drawingVisual = new DrawingVisual();
_drawingContext = _drawingVisual.RenderOpen();
_isReady = true;
}));
}
// ... compositing methods below
}