英文:
Background thread and event handler running in Blazor Component
问题
我遇到了一个问题,无法让一个简单的Blazor组件正常工作。当表单中的按钮被按下时,该组件应该启动一个后台线程,通过SSE HTTP调用向列表中添加一个新元素。在下面的代码中,问题是事件处理程序从未被调用,新消息也没有被呈现。我认为问题可能是由于StartAsync()调用阻塞,但我似乎无法将其在新线程上运行。
输出结果为:
message 0
message 1
message 2
Starting
我期望的输出是:
message 0
message 1
message 2
Starting
Component message from SSE
Component message from SSE
Component message from SSE
Component message from SSE
...
英文:
I'm having a problem getting a simple Blazor Component working. When a button in the form is pressed, the Component should kick off a background thread that adds a new element to a list (Using an SSE HTTP call). In the code below, the problem is that the event handler is never called, and the new messages are not rendered. I think the problem is due to the StartAsync() call blocking, but I can't seem to get it running on a new thread.
namespace BlazorTest
{
public class DeepViewerComponent : ComponentBase
{
internal string SecretKey;
internal string PublishableKey;
private void OnNewMessage(string message)
{
this.Messages.Add(message);
this.StateHasChanged();
}
private async Task ComponentMessageReceived()
{
this.Messages.Add("Component message from SSE");
await this.InvokeAsync(StateHasChanged);
}
internal async Task Subscribe()
{
for (int i = 0; i < 3; i++)
{
await Task.Delay(500);
this.OnNewMessage($"message {i}");
}
this.sandBoxClient = new IEXCloudClient(publishableToken: "a", secretToken: "b", signRequest: false, useSandBox: true);
this.sseClient = sandBoxClient.SSE.SubscribeCryptoQuoteSSE(new List<string>() { "btcusdt" });
sseClient.MessageReceived += async (s) => await ComponentMessageReceived();
this.OnNewMessage("Starting");
await sseClient.StartAsync();
this.OnNewMessage("Started");
this.OnNewMessage("Done");
}
}
}
The output is:
message 0
message 1
message 2
Starting
I expect the output to be:
message 0
message 1
message 2
Starting
Component message from SSE
Component message from SSE
Component message from SSE
Component message from SSE
...
答案1
得分: 3
-
It works on Server-side
-
它在服务器端运行
-
It hangs on Client-side
-
它在客户端卡住了
-
Blazor client-side is absolutely single-threaded (a JS / Browser limitation) so when StartAsync() needs a thread (to run async) then it will block when running in the client.
-
Blazor客户端是绝对单线程的(这是JS /浏览器的限制),因此当StartAsync()需要一个线程(用于异步运行)时,它会在客户端运行时阻塞。
-
Conclusion: this API is not suitable for running inside the Browser.
-
结论:这个API不适合在浏览器内运行。
英文:
- It works on Server-side
- It hangs on Client-side
Blazor client-side is absolutely single-threaded (a JS / Browser limitation) so when StartAsync() needs a thread (to run async) then it will block when running in the client.
Conclusion: this API is not suitable for running inside the Browser.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论