How to simulate latency on Blazor Server Side?

Viewed 357

I have a Blazor server side application that I will host on a server that isn't that near from the place that my main users will be using and I want to simulate if some feature is usable with some latency or if latency will really affect it.

But I can't test the latency while developing and I don't want to run the build in the server every time I want to test some change.

I have tried a lot of things, like reducing the internet connection in chrome developer tools, but it isn't the same as the latency from a far away host.

How can I simulate latency on Blazor Server Side?

2 Answers

You can use the Task.Delay() method inside a async Task function, just before fetching some data or before doing the stuff you need to simulate.

The next example is a blazor component that pretend to load a message from the server (MessageFromServer property) after clicking on the Button. the await Task.Delay method add that extra wait time.

@MessageFromServer

<button @onclick="ElaborateDataOnServer">Load Data</button>

@code{
    public string MessageFromServer { get; set; } = string.Empty;

    public async Task ElaborateDataOnServer()
    {
        //simulate the waiting
        await Task.Delay(1000);
        MessageFromServer = "loaded from server";
    }
}

Just add a custom ASPNET middleware and configure default transport to be LongPolling:

In Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            // Simulate cloud latency ...
            app.Use(async (context, next) =>
            {
                await Task.Delay(35);
                await next.Invoke();
                await Task.Delay(35);
            });

            app.UseEndpoints(endpoints =>
            {
                // Use slowest transport mode for testing
                endpoints.MapBlazorHub(options =>
                {
                    options.Transports = HttpTransportType.LongPolling;
                });
                endpoints.MapFallbackToPage("/_Host");
            });
        }
Related