Blazor: Timer Example - Refresh Data
[删除(380066935@qq.com或微信通知)]
更好的阅读体验请查看原文:https://www.prowaretech.com/articles/current/blazor/wasm/timer-refresh-rest-api-data#!
Blazor: Timer Example - Refresh Data
This code is compatible with .NET Core 3.1, .NET 5 and .NET 6. If using .NET 5 then follow the .NET Core 3.1 code.
Here is an example that uses the timer System.Threading.Timer
to refresh the data on the user's screen. It should be run as client-side Blazor WASM code.
For an example of the Timer
class running an analog clock,
.NET 6 Example
Here is a .NET 6 razor page that uses the Timer
. It is an example that needs to call StateHasChanged()
. The code for the RESTful API is just the default code for "WeatherForecast" controller that Microsoft adds when creating a new project.
@page "/fetchdata"
@using BlazorTimer.Shared
@inject HttpClient Http
<PageTitle>Weather forecast</PageTitle>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server using a timer.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
private System.Threading.Timer? timer; // NOTE: THIS LINE OF CODE ADDED
protected override async Task OnInitializedAsync()
{
// NOTE: THE FOLLOWING CODE ADDED
timer = new System.Threading.Timer(async (object? stateInfo) =>
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
StateHasChanged(); // NOTE: MUST CALL StateHasChanged() BECAUSE THIS IS TRIGGERED BY A TIMER INSTEAD OF A USER EVENT
}, new System.Threading.AutoResetEvent(false), 2000, 2000); // fire every 2000 milliseconds
}
}
Run this code and watch the "fetchdata" page update the weather forecast every couple seconds. It is just that simple!
Here is the standard WeatherForecastController
code that is supplied by Microsoft. It is unmodified.
using BlazorTimer.Shared;
using Microsoft.AspNetCore.Mvc;
namespace BlazorTimer.Server.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Here is the standard WeatherForecast
class that is supplied by Microsoft. It is unmodified.