如何在Blazor服务器端模拟延迟



我有一个Blazor服务器端应用程序,我将在离我的主要用户将要使用的地方不太近的服务器上托管它,我想模拟某个功能是否在一定延迟的情况下可用,或者延迟是否真的会影响它。

但我无法在开发时测试延迟,也不想每次测试一些更改时都在服务器中运行构建。

我尝试了很多方法,比如在chrome开发工具中减少互联网连接,但这与远程主机的延迟不同。

如何在Blazor服务器端模拟延迟?

您可以在异步Task函数中使用Task.Delay((方法,就在获取一些数据之前或在执行需要模拟的操作之前。

下一个例子是一个blazor组件,它假装在单击按钮后从服务器加载消息(MessageFromServer属性(。wait Task.Delay方法增加了额外的等待时间。

@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";
}
}

只需添加一个自定义的ASPNET中间件,并将默认传输配置为LongPolling:

在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");
});
}

最新更新