'Async adding children to a canvas

The code I'm working on displays rectangles on a canvas. This is giving me trouble so I wrote a simple version that has these relevant parts:

Private Async Sub RunAsync(sender As Object, e As RoutedEventArgs) Handles btnRun.Click
    Halt = False
    Nr = 0
    Do
        Await Task.Run(New Action(AddressOf DisplaySegment))
        GenerateNextSegment()
    Loop Until Halt
End Sub

Private Sub DisplaySegment()
    Dispatcher.Invoke(New Action(
    Sub()
        If rec IsNot Nothing Then canMain.Children.Add(rec)
    End Sub))
    Thread.Sleep(100)
End Sub

This works so I used this concept to program the real simulation:

Private Async Sub RunScenarioAsync(sender As Object, e As RoutedEventArgs) Handles btnRun.Click
    Halt = False
    Dim Iterations As Integer = 0
    Do
        Await Task.Run(New Action(AddressOf DisplaySegment))
        GenerateNextSegment()
        Iterations += 1
    Loop Until Halt
End Sub

Private Sub DisplaySegment()
    Dim Cell As Shapes.Rectangle
    For Each Sell As Cell In CurrentSegment.Cells
        <Code to compute Cell properties>
        Cell = New Rectangle With
            {
            .Fill = New SolidColorBrush(CellColor),
            .Height = CurrentScenario.CellSize,
            .Width = CurrentScenario.CellSize
            }
        Canvas.SetLeft(Cell, CellLeft)
        Canvas.SetTop(Cell, CellTop)
        Dispatcher.Invoke(New Action(Sub()
                                          canMain.Children.Add(Cell)
                                     End Sub))
    Next
End Sub

This fails with the exception: "The calling thread must be STA, because many UI components require this." But the only difference between the two concepts is that in the latter code the Dispatcher is inside a For loop. Does that account for the exception? If so, what is the right approach? If not, what is wrong with my code?

Also note that I have reviewed the numerous posts regarding that exception but most are over a decade old and deal with background worker threads so not applicable here.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source