ASP.NET Core SignalR version 2.1 offers streaming from the server to the client. Using ASP.NET Core 3.0, streams can also be sent from the client to the server. C# 8 gives a new syntax for asynchronous streaming. The new syntax is available with the new SignalR version.

This article compares streaming using SignalR with the old and new C# 8 syntax.

Stream to the client returning a ChannelReader

Let’s start returning a stream of SomeData objects from the server to the client. The method GetSomeDataWithChannelReader can be invoked with the number of items returned, and the delay that should be used between sending each item along with an option to cancel the stream from the client. The Channel class used here (from the namespace System.Threading.Channels) allows readers and writers for a stream of data. The method CreateBounded returns a channel with a maximum capacity, the method CreateUnbounded that is used here offers an unlimited capacity. The reader of this channel is returned to the client, whereas the writer is passed to the method WriteItemsAsync. The WriteItemsAsync method uses the ChannelWriter to send data to the client:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

**public** **class** ServerToClientStreamingHub : Hub

{

**public** ChannelReader<SomeData> GetSomeDataWithChannelReader(

**int** count,

**int** delay,

CancellationToken cancellationToken)

{

**var** channel = Channel.CreateUnbounded<SomeData>();

_ = WriteItemsAsync(channel.Writer, count, delay, cancellationToken);

**return** channel.Reader;

}

**private** **async** Task WriteItemsAsync(

ChannelWriter<SomeData> writer,

**int** count,

**int** delay,

CancellationToken cancellationToken)

{

**try**

{

**for** (``**var** i = 0; i < count; i++)

{

cancellationToken.ThrowIfCancellationRequested();

**await** writer.WriteAsync(``**new** SomeData() { Value = i });

**await** Task.Delay(delay, cancellationToken);

}

}

**catch** (Exception ex)

{

writer.TryComplete(ex);

}

writer.TryComplete();

}

}

#.net core #asp.net core #csharp #aspnetcore #csharp8 #signalr

Async Streaming with ASP.NET Core SignalR and C# 8
16.80 GEEK