dotnet / dotnet/dotnet-api-docs

ConfiguredCancelableAsyncEnumerable.WithCancellation needs an example

Open
#1,887 1 comment 0 reactions 0 assignees View on GitHub
area-System.Threading.Tasks dotnet-api/prod Pri2 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

An example of how to use this method would be appreciated. For example, suppose I have a class that streams out messages in a .NET Core 3.0 C# 8.0 beta project:

```
public class StreamGenerator
{
public async IAsyncEnumerable GetMessageStream()
{
for (int i = 0; i < 5; i++)
{
await Task.Delay(500);
yield return $"Message {i + 1}";
}
}
}
```

Then I can use it like so:

```
var incommingMessages = new StreamGenerator();
await foreach (var message in incommingMessages.GetMessageStream())
{
Console.WriteLine(message);
}
```

Now suppose I want cancellation support. Just to sanity check let's cancel the token even before we start streaming in messages:

```
var cts = new CancellationTokenSource();
cts.Cancel();
var incommingMessages = new StreamGenerator();
await foreach (var message in incommingMessages.GetMessageStream().WithCancellation(cts.Token))
{
Console.WriteLine(message);
}
```

The expected behavior would be that an OperationCanceledException occurs, but this is not the case. The await foreach loop runs as if no cancellation had been requested.

Could you provide an example of how to use this extension method?

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: 421b581f-d44b-1f32-f211-fd261e505c42
* Version Independent ID: 8bd92f2e-1e49-ec33-fd56-0187807d7604
* Content: [TaskExtensions.WithCancellation(IAsyncEnumerable<T>, CancellationToken) Method (System.Threading.Tasks)](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskextensions.withcancellation?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.Threading.Tasks.TaskExtensions.WithCancellation``1)%3Bk(DevLang-csharp)%26rd%3Dtrue)
* Content Source: [xml/System.Threading.Tasks/TaskExtensions.xml](https://github.com/dotnet/dotnet-api-docs/blob/master/xml/System.Threading.Tasks/TaskExtensions.xml)
* Product: **dotnet-api**
* GitHub Login: @dotnet-bot
* Microsoft Alias: **dotnetcontent**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.