0
votes

After exploring a lot, we don't have a blazor component stopwatch. I need to display Elapsed time in blazor page Below was my code, we can calculate elapsed time with start and stop button I am kind of stuck on how to call and display elapsed time in blazor page. Any suggestion?

@using System.Diagnostics;

<p> <button @onclick=@Start>Start</button></p>
<p> <button @onclick=@Stop>Stop</button></p>

@code
{    
    protected override void OnInitialized()
    {
        base.OnInitialized();
        Stopwatch sw = new Stopwatch();
        TimeSpan tt1 = TimeSpan.Zero;    
    }

    private double elapsedtime;
    private DateTime startTime;
    private DateTime stopTime;
    private bool running = false;

    public void Start()
    {
        this.startTime = DateTime.Now;
        this.running = true;
    }

    public void Stop()
    {
        this.stopTime = DateTime.Now;
        this.running = false;
    }

    public double ElapsedTimeSecs()
    {
        TimeSpan interval;
        if (running)
            interval = DateTime.Now - startTime;
        else
            interval = stopTime - startTime;
        return interval.TotalSeconds;
    }
}
2

2 Answers

1
votes

As has been stated by Henk Holterman, you need a Timer. But in order to make the actions executed by timers thread safe and controllable (pause, resume, stop etc) you'd need a lot of boiler plate code.

I have created a stopwatch demo in Blazor, where the Timer based operations are handled by a library called Recurop, which abstracts a Timer action into a RecurringOperation object and makes the code a lot simpler and cleaner and it enables you to bind UI element properties to react to changes in the state/status of the recurring operation (timer action). For example, enable a "pause" button when the operation is running, but disable the "pause" button when the operation is stopped, etc.

If you want to see the Blazor stopwatch web page in action, go to: https://tdmr87.github.io/BlazorStopwatchWithRecurop/

If you want to see the code for the stopwatch demo in Blazor, go to: https://github.com/TDMR87/BlazorStopwatchWithRecurop

If you're interested in the library for handling recurring operations (timers), then go to Recurop github page: https://github.com/TDMR87/Recurop

Recurop is my personal project and it is available on NuGet if you want to play around with it.

Cheers

1
votes

You need a Timer:

@implements IDisposable

...

private System.Threading.Timer _timer;

public void Start()
{
    this.startTime = DateTime.Now;        
    _timer = new System.Threading.Timer(async _ =>
    {
        elapsedtime = ElapsedTimeSecs();
        await InvokeAsync(StateHasChanged);
    }, null, 0, 1000);
}

public void Stop()
{
    this.stopTime = DateTime.Now;
    _timer?.Dispose();
    _timer = null;
}

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

and then display elapsedtime how and where you want it.