如何在套接字接收事件后更新Blazor(托管)

时间:2019-02-17 12:27:49

标签: multithreading websocket blazor

你好,我有一个想显示变量的页面。 此变量从另一个线程(任务-通过websocket接收数据)获取更新,我想以线程安全的方式显示它:

Blazor Page

@page "/new"
@inherits NewBase
<button onclick="@(async()=>await OnRunPressed())" class="control-button">Run</button>
NewValue :@socketString

public class NewBase:BlazorComponent
    {
        [Inject] protected BenchService service { get; set; }

        protected CancellationTokenSource src = new CancellationTokenSource();
        protected string socketString;

        protected async Task OnRunPressed()
        {
            Task updateTask= Task.Run(async () =>
            {
                var buffer =new byte[1024];
                ClientWebSocket socket = new ClientWebSocket();
                await socket.ConnectAsync(new Uri("ws://localhost:8500/monitor"), CancellationToken.None);
                while (true)
                {

                    await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                    this.socketString = Encoding.UTF8.GetString(buffer);
                    this.StateHasChanged();
                }

            },src.Token);
            await this.service.HitServerAsync(); //does some stuff while the above task works
            src.Cancel();
        }
    }

更新 感谢@Dani现在我终于至少得到一个错误:

blazor.server.js:16 POST http://localhost:8500/_blazor/negotiate 500 (Internal Server Error)
Error: Failed to start the connection: Error: Internal Server Error

2 个答案:

答案 0 :(得分:2)

StateHasChanged();方法末尾,您可能缺少OnRunPressed

我猜这是服务器端的Blazor,对吗?

如果没有,那么您应该知道WASM上的Mono当前为单线程...

答案 1 :(得分:1)

通过websocket接收数据后,他们没问题要调用StateHasChanged();。一切都应该运行。我已经对其进行了测试(作为服务器端),并且可以正常运行:

https://github.com/ctrl-alt-d/blazorTestingWebSocketsServerSide/tree/master

enter image description here

此外,我已经将它作为客户端wasm进行了测试,这是几个问题:

  1. 您正在使用ArrayPool,它是非netstandard2.0类。
  2. WebSocket无法从wasm连接。