Why does my code work only once?

RogerSchlueter-7899 1,761 Reputation points
2026-08-22T02:35:16.3133333+00:00

My application includes a stopwatch plus a lap counter. The stopwatch is working fine using the following code:

Private Sub StartTimer(sender As Object, e As RoutedEventArgs) Handles btnStart.Click
	CurrentTime = TimeSpan.Zero
	LapTime = TimeSpan.Zero
	LapCount = 0
	tmr = New Timer(1000) With {.Enabled = True}
	AddHandler tmr.Elapsed, AddressOf UpdateClock
End Sub

Private Sub UpdateClock(source As Object, e As ElapsedEventArgs)
	Dispatcher.Invoke(Sub() PopulateTimer())
End Sub


Private Sub PopulateTimer()
	CurrentTime = CurrentTime.Add(OneSecond)
	txtDuration.Text = CurrentTime.ToString
End Sub

Saving laps uses this code:

Public Property Laps As List(Of Lap)

Private Sub CreateLap(sender As Object, e As RoutedEventArgs) Handles btnLap.Click
	Dim t As Task = Task.Run(
		Sub()
			SaveLap()
		End Sub)
End Sub

Private Sub SaveLap()
	LapTime = CurrentTime - LapTime
	LapCount += 1
	Laps.Add(New Lap With {.Count = LapCount, .Duration = LapTime})
	RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(NameOf(Laps)))
	LapTime = CurrentTime
End Sub

The XAML for showing laps is as follows:

<DataGrid
	x:Name="dgLaps"
	AutoGenerateColumns="False"
	ItemsSource="{Binding Path=Laps}"
	Margin="0,0,10,0">
	<DataGrid.Columns>
		<DataGridTextColumn
			Binding="{Binding Path=Count}"
			Header="Lap"
			Width="30" />
		<DataGridTextColumn
			Binding="{Binding Path=Duration}"
			Header="Duration"
			Width="*" />
	</DataGrid.Columns>
</DataGrid>

This all works - for the first lap. After that, the SaveLap subroutine is processed but the additional laps are not displayed in the DataGrid. I have confirmed that Laps does contain all the added laps so that is not the problem. Why does the code only work once?

Developer technologies | VB

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,951 Reputation points
    2026-08-22T17:20:16.14+00:00

    Just like in UpdateClock, you need to use Dispatcher.Invoke() to call RaiseEvent PropertyChanged so it runs on the ui thread.

    Was this answer helpful?

    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.