How to wait for speech recognition callback

Brian Erickson 346 Reputation points

I've got the Android speech recognition stuff working well but have a question.

I've got a method called StartListening(). It's starts the speech recognition mechanism and when the OnResult call back gets fired the caller is notified via an event notification.

Now, what I'd like is a method call Listen. It should return a string consisting of the words spoken by the user. The best I've been able to come with is:

      async public Task<string> Listen()
         Words = null;
         GlobalVariables.SpokenWords.SpokenWordsEvent += SpokenWordsEventHandler;
         Device.BeginInvokeOnMainThread(() =>

         while (Words == null)
            await Task.Delay(100);

         GlobalVariables.SpokenWords.SpokenWordsEvent -= SpokenWordsEventHandler;

         return (Words);

It does work but is very ugly. I'm sure there's a better way but I don't see it...any help? It would be ideal if it was not marked async...

A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,325 questions
0 comments No comments
{count} votes

Accepted answer
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points


    Welcome to Microsoft Q&A!

    Take a look at TaskCompletionSource , It enables the creation of a task that can be handed out to consumers.

       public Task<string> MyTask()  
           var tcs = new TaskCompletionSource<string>();  
               //OnResult call back  
           return tcs.Task;  

    BTW , I would suggest you use official sample for SpeechToText.

    We could handle the callback in OnActivityResult method in activity.

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

0 additional answers

Sort by: Most helpful