How to continuously update the display in a loop calculation

RogerSchlueter-7899 1,526 Reputation points
2021-12-31T17:23:52.327+00:00

I'm working on a simulation model that uses the following iterative loop:

Private Sub RunScenario(sender As Object, e As RoutedEventArgs) Handles btnRun.Click
Do
    DisplaySegment()
    GenerateNextSegment()
    Loop Until Halt
End Sub

where Halt is a Boolean that GenerateNextSegment sets to True when certain conditions are met.

DisplaySegment displays the current Segment by adding various shapes to a canvas. At the present time, that loop runs in the UI thread. As a result the canvas is not updated until the loop is Halted. I would like to actually display the result of each iteration so I can manually stop the loop if things start to go South.

Note that GenerateNextSegment obliterates the CurrentSegment in the process of creating the next one with the result that DisplaySegment has to finish its work before GenerateNextSegment begins; as well, GenerateNextSegment has to finish before DisplaySegment can be called. How can I implement the main loop yet have the canvas actually updated on the monitor at each iteration.

Developer technologies | Windows Presentation Foundation
Developer technologies | VB
{count} votes

2 answers

Sort by: Most helpful
  1. WayneAKing 4,931 Reputation points
    2021-12-31T18:25:53.9+00:00

    I can't tell from the small snippet you posted or from your
    description exactly what kind of control is being used for
    the display. Therefore I can only offer a general observation.

    It is common for displays to be "tardy" in showing changes,
    especially in tight loops or during pauses (such as Sleep).

    When you make a change to the contents of a visual control,
    actual updating occurs according to the activities of the
    control and Windows itself. Therefore it is customary to
    force an immediate visible change in the control by explicitly
    calling the Update() or Refresh() method/function of the
    control after every change to its contents.

    • Wayne
    0 comments No comments

  2. Peter Fleischer (former MVP) 19,341 Reputation points
    2022-01-01T21:15:22.433+00:00

    Hi,
    you can use Await and Dispatcher in second thread like in following demo.

    Because it's impossible to post code ("WAF v2 has determined your request exceeded the normal web request and has blocked your request.") see attached txt.

    161703-x.txt

    Result:

    161687-x.gif

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.