gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:18:54 38 4
gpt4 key购买 nike

您好,我有一个blazor页面,我想在其中显示一个变量。
这个变量从另一个线程(通过Websocket接收数据的另一个线程)获取更新,我想以线程安全的方式显示它:

Blazor页面

@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

最佳答案

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

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

enter image description here

另外,我已经将它作为客户端wasm进行了测试,它们有几个问题:

  • 您使用的是非netstandard2.0类的ArrayPool
  • WebSocket无法从wasm连接。
  • 关于multithreading - 如何在套接字接收事件后更新Blazor(托管),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733243/

    38 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com