如何返回任务?

问题描述

我正在从以下网站学习Websocket:https://radu-matei.com/blog/aspnet-core-websockets-middleware/如何从下面的任务中返回?

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);


        });
    }

我得到了:严重性代码说明项目文件行抑制状态 错误CS0161'NotificationsMessageHandler.ReceiveAsync(WebSocket,WebSocketReceiveResult,byte [])':并非所有代码路径都返回值

我不知道如何返回任务。

解决方法

您不需要Task。显式运行,而不是

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);


    });

您可以使用

await socket.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.ASCII.GetBytes(message),cancellationToken: CancellationToken.None);

在这里,await将返回socket.SendAsync的结果,我假设它是异步的