你好,我有一个想显示变量的页面。 此变量从另一个线程(任务-通过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
答案 0 :(得分:2)
在StateHasChanged();
方法末尾,您可能缺少OnRunPressed
我猜这是服务器端的Blazor,对吗?
如果没有,那么您应该知道WASM上的Mono当前为单线程...
答案 1 :(得分:1)
通过websocket接收数据后,他们没问题要调用StateHasChanged();
。一切都应该运行。我已经对其进行了测试(作为服务器端),并且可以正常运行:
https://github.com/ctrl-alt-d/blazorTestingWebSocketsServerSide/tree/master
此外,我已经将它作为客户端wasm进行了测试,这是几个问题:
ArrayPool
,它是非netstandard2.0类。