Why is a Completed Task Halting Processing

RogerSchlueter-7899 1,426 Reputation points
2025-04-12T05:49:07.7466667+00:00

Working with a map application, I am trying to allow the user to click on a series of points on a map to create a line segment. With the help here, I have the following code:

PrivateCreatingPoint As TaskCompletionSource(Of Point)

Private Sub CreatePoint(sender As Object, e As MouseButtonEventArgs) Handles map.MouseLeftButtonUp
	If Keyboard.Modifiers = ModifierKeys.Control AndAlso CreatingPoint IsNot Nothing Then
		Dim pt As Point = map.ScreenToGeographic(e.GetPosition(map))
		Points.Add(pt)
		CreatingPoint.SetResult(pt)  << Stops here with error>>
	End If
End Sub

Private Async Sub AddPoint()
	CreatingPoint = New TaskCompletionSource(Of Point)
	'Pauses execution until CreatePoint is invoked by using the mouse
	'Execution continues here after a point is created
	Dim pt As Point = Await CreatingPoint.Task
	Dim PointData As ValueTuple(Of Double, Double, Double, Double) = Await GetElevation(pt)
	....  <<code that displays the new poinit and saves it to a database>>
End Sub

This works just fine - for the first click. On the second click I get this error message when the code reaches the line Marked in the code snippet:

An attempt was made to transition a task to a final state when it had already completed.

I don't understand why I can't create a new TaskCompletionSource once the previous task has run to completion.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,827 questions
{count} votes

Your answer

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