DrawingGroup -交叉线程

本文关键字:线程 DrawingGroup | 更新日期: 2023-09-27 17:50:48

我有一个类,有两个字段和一些绘图方法:

public class DrawingTool
{
    private readonly DrawingGroup _drawingGroup;
    private DrawingImage _imageSource;
    public DrawingTool()
    {
        _drawingGroup = new DrawingGroup();
        _imageSource = new DrawingImage(_drawingGroup);
    }
    public DrawingImage GetImageSource()
    {
        return _imageSource;
    }
    public void DrawSomething()
    {
        using (DrawingContext dc = _drawingGroup.Open()) // HERE'S AN ERROR - _drawing group is being used by another thread (InvalidOperationException)
        {
           // draw something here
        }
    }
}

这是一个WPF项目,所以我也有一个Image:

<Image x:Name="MyImage" Width="320" Height="240"></Image>

我设置的来源:

_drawingTool = new DrawingTool();
Dispatcher.Invoke(() => MyImage.Source = _drawingTool.GetImageSource());
_device.FrameReady += (sender, args) => Dispatcher.Invoke(() =>
{
    _drawingTool.DrawSomething();
});

我从评论中得到一个错误…我试图调用DrawSomething()方法,并在DrawSomething()中使用CheckAccess()_drawingGroup -没有帮助。如何使其工作成为可能?提前感谢您的帮助!

[编辑1。)
也许我应该用一些不同于DrawingGroup的东西?

[编辑2。)
没人知道吗?(

DrawingGroup -交叉线程

好了,我找到解决办法了…很明显……我必须在主线程中初始化整个绘图工具(在主窗口构造函数中),然后设置MyImage.Source(也在同一个地方)。现在一切都好了!:)