andrew
andrew

Reputation: 571

Background thread and event handler running in Blazor Component

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
...

Upvotes: 1

Views: 2818

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273169

  1. It works on Server-side
  2. 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.

Upvotes: 3

Related Questions