Skip to content

Commit 0b20e3f

Browse files
Copilotjfversluis
andauthored
Add CancellationToken explanation to SpeechToText docs (#636)
* Initial plan * docs: add CancellationToken explanation and fix undefined variable in SpeechToText docs Co-authored-by: jfversluis <939291+jfversluis@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: jfversluis <939291+jfversluis@users.noreply.github.com>
1 parent 6322fde commit 0b20e3f

1 file changed

Lines changed: 9 additions & 2 deletions

File tree

docs/maui/essentials/speech-to-text.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ Add permissions to `tizen-manifest.xml`:
5959

6060
The `SpeechToText` can be added to a .NET MAUI application in the following way.
6161

62+
> [!NOTE]
63+
> The methods in this API accept a `CancellationToken` to cancel asynchronous operations. A `CancellationToken` can be obtained by creating a [`CancellationTokenSource`](/dotnet/api/system.threading.cancellationtokensource) and accessing its `.Token` property. You can also use `CancellationToken.None` if you don't need to cancel the operation. For more detail on how to provide a `CancellationToken` refer to the [Microsoft documentation](/dotnet/standard/threading/cancellation-in-managed-threads).
64+
6265
### Request permissions
6366

6467
Developers must manually request Permissions.Microphone and also call ISpeechToText.RequestPermissions():
@@ -197,6 +200,7 @@ Now you can inject the service like this:
197200
public partial class MainPage : ContentPage
198201
{
199202
private readonly ISpeechToText speechToText;
203+
private CancellationTokenSource? cancellationTokenSource;
200204

201205
public MainPage(ISpeechToText speechToText)
202206
{
@@ -206,14 +210,17 @@ public partial class MainPage : ContentPage
206210

207211
public async void Listen(object sender, EventArgs args)
208212
{
209-
var isGranted = await speechToText.RequestPermissions(cancellationToken);
213+
cancellationTokenSource?.Cancel();
214+
cancellationTokenSource = new CancellationTokenSource();
215+
216+
var isGranted = await speechToText.RequestPermissions(cancellationTokenSource.Token);
210217
if (!isGranted)
211218
{
212219
await Toast.Make("Permission not granted").Show(CancellationToken.None);
213220
return;
214221
}
215222

216-
await speechToText.StartListenAsync(new SpeechToTextOptions { Culture = CultureInfo.CurrentCulture, ShouldReportPartialResults = true }, CancellationToken.None);
223+
await speechToText.StartListenAsync(new SpeechToTextOptions { Culture = CultureInfo.CurrentCulture, ShouldReportPartialResults = true }, cancellationTokenSource.Token);
217224
}
218225
}
219226
```

0 commit comments

Comments
 (0)