It seems that Blazor makes it easy for the client to call a server's method using something called SignalR underneath. But when I searched if Blazor does that for the other direction, the answer was that Blazor does not do that and I have to implement it myself using SignalR. So, I thought about polling.
That is, I like to read a property or call a method in the server's object at an interval to determine if something has changed. To test this, I added this property to the WeatherForecastService
class. The property increases every time when read.
int _Value = 0;
public int Value
{
get
{
_Value++;
return _Value;
}
}
In the weather tablet sample plage, I removed the code to display the weather and added this.
<p>This component demonstrates fetching data from a service.</p>
<div>Value = @this.Value</div>
@code {
private int Value = 0;
protected override async Task OnInitializedAsync()
{
System.Timers.Timer t = new System.Timers.Timer();
t.Elapsed += (s, e) => { Value = ForecastService.Value; };
t.Interval = 1000;
t.Start();
}
}
And it did not work. I found an existing question, but it uses F# which I don't understand, and I don't know what ClientTImer
is, so the answer was not helpful to me.
t.Elapsed += async (s, e) =>
{
Value = ForecastService.Value;
await InvokeAsync(StateHasChanged);
};