We've established that you're using .NET 4.0, so SemaphoreSlim
goes out the window.
First I'd try getting around the problem by sharing an instance of SpeechSynthesizer
and using SpeakAsyncCancelAll
when a new request comes in:
Private SpeechSynthesizer As New SpeechSynthesizer
Private Sub NewRecallLabel_TextChanged(sender As Object, e As EventArgs)
Dim myrecalllabel As Label = TryCast(sender, Label)
SpeechSynthesizer.SpeakAsyncCancelAll()
SpeechSynthesizer.SpeakAsync("Ticket number " & TTSTicket & ", please proceed to counter " & TTSCounter)
End Sub
Oringinal answer
Since you can't use SyncLock
in an async context and you want non-blocking execution, your best bet is to use a SemaphoreSlim(1, 1)
to get async mutex semantics (similar to what @Gubr suggested, except async):
Private Semaphore As New SemaphoreSlim(1, 1)
Private Sub NewRecallLabel_TextChanged(sender As Object, e As EventArgs)
Dim myrecalllabel As Label = TryCast(sender, Label)
Dim SpeechSynthesizer As New SpeechSynthesizer
Await Semaphore.WaitAsync()
Try
' We're inside the protected region now.
Await SpeechSynthesizer.SpeakAsync("Ticket number " & TTSTicket & ", please proceed to counter " & TTSCounter)
Finally
Semaphore.Release()
End Try
End Sub
I'd also consider wiring in some form of throttling and/or auto-cancellation, because the code as it stands will not work very well if the label text changes rapidly (i.e. each subsequent speech request will have to wait for previous ones to complete).