Martin Michaelsen
Martin Michaelsen

Reputation: 125

Blazor Server Side Timer is running amok

I have this ServerSide Blazor running and I have:

listTimer = new System.Timers.Timer();
        listTimer.Interval = 1000;
        listTimer.Elapsed += async (s, e) =>
        {
            await Utils.LogToConsole(jsRuntime, DateTime.Now.ToString());
        }

    `

But when I run this I get huge amounts of log in the Chrome console but I expect to see only logs each 1000 millis. Anyone seen this problem and found a workaround. Yes I could check the actual time and compare but I dont like it triggering like thats crazy.

Upvotes: 2

Views: 1403

Answers (3)

Tiago Alves
Tiago Alves

Reputation: 37

The exact same hapens to me, but it doesn't seem like Dispose() is being called at all.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273244

... I get huge amounts of log in the Chrome console

That can only happen when you create and assign the Timer more than once.

You didn't post that code but I guess you need something like:

if (listTimer == null)
{
    listTimer = new System.Timers.Timer();
    listTimer.Interval = 1000;
    listTimer.Elapsed += async (s, e) =>
    {
        await Utils.LogToConsole(jsRuntime, DateTime.Now.ToString());
    }
}

and a Timer is IDisposable , so add:

@implements IDisposable

and this to @code:

public void Dispose()
{
    listTimer?.Dispose();
}

Upvotes: 2

boindiil
boindiil

Reputation: 5865

You habe to unsubscribe the timer-Event when disposing the component. The easiest way to do that ist disposing the timer itself.

@using System
@implements IDisposable

@code {
    public void Dispose()
    {
        listTimer?.Dispose();
    }
}

Upvotes: 5

Related Questions