Reputation: 111
I am learning Websocket from: https://radu-matei.com/blog/aspnet-core-websockets-middleware/ How do I return from a Task below?
public override Task ReceiveAsync(WebSocket socket, WebSocketReceiveResult result, byte[] buffer)
{
string message = "Replied by: " + cn.GetId(socket);
Task.Run(async () =>
{
await socket.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.ASCII.GetBytes(message),
offset: 0,
count: message.Length),
messageType: WebSocketMessageType.Text,
endOfMessage: true,
cancellationToken: CancellationToken.None);
});
}
I got: Severity Code Description Project File Line Suppression State Error CS0161 'NotificationsMessageHandler.ReceiveAsync(WebSocket, WebSocketReceiveResult, byte[])': not all code paths return a value
and I don't know how to return a Task..
Upvotes: 0
Views: 251
Reputation: 706
You don't need Task.Run explicitly, Instead of
Task.Run(async () =>
{
await socket.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.ASCII.GetBytes(message),
offset: 0,
count: message.Length),
messageType: WebSocketMessageType.Text,
endOfMessage: true,
cancellationToken: CancellationToken.None);
});
you can just use
await socket.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.ASCII.GetBytes(message),
offset: 0,
count: message.Length),
messageType: WebSocketMessageType.Text,
endOfMessage: true,
cancellationToken: CancellationToken.None);
here, await will return the result of socket.SendAsync which i am assuming is asynchronous
Upvotes: 2