stopwatch in .NetMaui is not accurate

175 Views Asked by At

Hi The stopwatch that I have made is not accurate(millisecond precision) - it is slow. How can I change that? I also would like to make timer counting down. There is literally no tutorials or any information how to do that. Do you have any solutions? Do you know any useful videos or internet pages?

MainPage

    <StackLayout 
    VerticalOptions="Center">
    
    <Label 
        x:Name="timeLable"
        Text="0:000"
        TextColor="White"
        FontSize="Header"
        HorizontalTextAlignment="Center"/>

    <StackLayout Orientation="Horizontal"
                 HorizontalOptions="Center"
                 Spacing="12"
                 Margin="0,60,0,0">

        <Button
            x:Name="startStopButton"
            BackgroundColor="Black"
            Clicked="OnStartStop"
            WidthRequest="60"
            HeightRequest="60"/>


        <Button
            x:Name="reset"
            BackgroundColor="Black"
            WidthRequest="60"
            Clicked="OnReset"
            HeightRequest="60"/>

    </StackLayout>

</StackLayout>

MainPage.cs

    public MainPage()
{
    InitializeComponent();
}

private TimeOnly time = new();
private bool isRunning;

private async void OnStartStop(object sender, EventArgs e)
{

    
    isRunning = !isRunning;

    while (isRunning)
    {
        time = time.Add(TimeSpan.FromMilliseconds(1));
        SetTime();
        await Task.Delay(TimeSpan.FromMilliseconds(1));
    }
}


private void SetTime()
{
    timeLable.Text = $"{time.Second}:{time.Millisecond:000}";
}


private void OnReset(object sender, EventArgs e)
{
    time = new TimeOnly();
    SetTime();
}
0

There are 0 best solutions below