Thread cannot access the object

后端 未结 1 1717
孤城傲影
孤城傲影 2021-01-20 17:16

I declared a field:

WriteableBitmap colorBitmap;

Then I created a simple thread which does something:

private void doSometh         


        
相关标签:
1条回答
  • 2021-01-20 17:37

    There are two problems with your code:

    1. You can't access the WriteableBitmap from another thread that is different than the one who created it. If you want to do that, you need to freeze your bitmap by calling WriteableBitmap.Freeze() first

    2. You can't access myImage.Source in a thread that is not the dispatcher thread.

    This should fix both of these two problems:

    private void doSomething()
    {
        // ... bla bla bla
        colorBitmap = new WriteableBitmap(/* parameters */);
        colorBitmap.Freeze();
        Application.Current.Dispatcher.Invoke((Action)delegate
        {
            myImage.Source = colorBitmap;
        });
    }
    

    EDIT Note that this approach allows you to create and update your bitmap wherever you want in your thread. Once the bitmap is frozen, it can no longer be modified in which case you should just trash it and create a new one.

    On a side note, if you wish not to block your thread updating myImage.Source use BeginInvoke instead of Invoke

    0 讨论(0)
提交回复
热议问题