2

I have a WP8 app, which uses the UI-less version of the SpeechRecognizer. I use the following code:

string[] commands = { "Shoot" };
recognizer = new SpeechRecognizer();
await speechOutput.SpeakTextAsync("You can say Shoot.");
recognizer.Grammars.AddGrammarFromList("captureCommands", commands);
SpeechRecognitionResult result = await recognizer.RecognizeAsync();

if (result.Text == "Shoot")
   cam.CaptureImage();

This prompts the user in both speech and on-screen text that he can say "Shoot" to take a photo. Three other options are:

  1. Tap the screen to shoot
  2. Click the shoot button in the ApplicationBar
  3. Click the a button on the ApplicationBar to choose from the photo library

In all three cases I would like to cancel the speech recognizer task. I tried removing the await and casting the IAsyncOperation<SpeechRecognitionResult> to a Task<SpeechRecognitionResult>, but since I don't create the task and the method does not take a cancellation token, I don't know how to cancel it, even now that I have the task object.

If I don't cancel the task and navigate away from the page, I get an App level exception. Is there a way I can explicitly cancel the task or awaited operation?

Elad Lachmi
  • 10,406
  • 13
  • 71
  • 133

1 Answers1

2

You can't cancel a non-cancelable async operation. If the method doesn't take a cancellation token you can't basically cancel it. What you can do is:

  1. Abandon the operation using WithCancellation or WithTimeout.
  2. Dispose the SpeechRecognizer (which is an IDisposable) and catch its ObjectDisposedException.

Here's my solution to a similar, though not the same, problem: Async network operations never finish

Community
  • 1
  • 1
i3arnon
  • 113,022
  • 33
  • 324
  • 344
  • 1
    Yes, I gathered as much. Well, it would pain me to do this workaround, since it feels so wrong, but I guess that's what I`ll end up doing :) Thank you! – Elad Lachmi Feb 25 '14 at 15:31