Click here to Skip to main content
15,901,666 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have develop the blazor application. In this application I had used

System.Threading.Timer for execute the Specific code for Specific interval

time.

C#
      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





but Timer not works when internet disconnected in my blazor application i.e

offline

could you please confirm timer works in offline or not.

please help me.

thanks

What I have tried:

but Timer not works when internet disconnected in my blazor application i.e 

offline

could you please confirm timer works in offline or not.
Posted
Updated 4-Feb-23 10:07am

1 solution

I gather that you are using this code example: Blazor: Timer Example - Refresh Data - PROWARE technologies[^]

Your lambda method is calling a remote endpoint. When offline, it will fail. So the Timer is working, just the data is not refreshed. You can check this by setting a breakpoint on the line:
C#
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");

The timer will execute the lambda method every two seconds.

You can check it by using this code:
XML
@page "/"

<h1>Tick Count: @tickCount</h1>

@code {
    private int tickCount = 0;
    private Timer? timer;

    protected override Task OnInitializedAsync()
    {
        timer = new Timer(stateInfo =>
        {
            tickCount += 1;
            InvokeAsync(StateHasChanged);
        }, new AutoResetEvent(false), 2000, 2000);

        return base.OnInitializedAsync();
    }
}

When run, the Tick Count will update every 2 seconds.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900