Blazor Server Side Timer is running amok
Asked Answered
B

3

2

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.

Burglar answered 22/6, 2020 at 11:6 Comment(1)
I have 3.1.300 preview015048Burglar
L
2

... 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();
}
Lindquist answered 22/6, 2020 at 12:22 Comment(2)
Thanks very much. I've done more Blazor WASM but now I understand more of the nature of Blazor Server:-)Burglar
You must dispose the timer too, or it will hang around foreverPrentiss
S
5

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();
    }
}
Stretchy answered 22/6, 2020 at 11:11 Comment(1)
@PeterMorris thanks for your comment, your solution is nicer. I have updated my answer.Stretchy
L
2

... 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();
}
Lindquist answered 22/6, 2020 at 12:22 Comment(2)
Thanks very much. I've done more Blazor WASM but now I understand more of the nature of Blazor Server:-)Burglar
You must dispose the timer too, or it will hang around foreverPrentiss
L
0

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

Leifleifer answered 18/11, 2022 at 17:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.