From c2725eba60bd71a811d5fb84705221793f2ac933 Mon Sep 17 00:00:00 2001 From: holger Date: Sat, 22 Jan 2022 22:26:20 +0100 Subject: [PATCH] split code and html --- WebAssembly/PageComponents/CounterBase.cs | 36 +++++++++++++++++++++ WebAssembly/Pages/Counter.razor | 39 +++-------------------- 2 files changed, 40 insertions(+), 35 deletions(-) create mode 100644 WebAssembly/PageComponents/CounterBase.cs diff --git a/WebAssembly/PageComponents/CounterBase.cs b/WebAssembly/PageComponents/CounterBase.cs new file mode 100644 index 0000000..2481888 --- /dev/null +++ b/WebAssembly/PageComponents/CounterBase.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Microsoft.AspNetCore.Components; + +namespace WebAssembly.PageComponents; + +public class CounterBase : ComponentBase +{ + public int CurrentCount { get; private set; } + public bool Cancel { get; private set; } + public Stopwatch Stopwatch { get; } = new(); + + public async Task Start() + { + Stopwatch.Start(); + Cancel = false; + while (!Cancel) + { + CurrentCount++; + StateHasChanged(); + await Task.Delay(10); + } + Stopwatch.Stop(); + } + + public void Stop() + { + Cancel = true; + } + + public void Reset() + { + Cancel = true; + CurrentCount = 0; + Stopwatch.Reset(); + } +} \ No newline at end of file diff --git a/WebAssembly/Pages/Counter.razor b/WebAssembly/Pages/Counter.razor index b3ee3e1..d01ec7c 100644 --- a/WebAssembly/Pages/Counter.razor +++ b/WebAssembly/Pages/Counter.razor @@ -1,45 +1,14 @@ @page "/counter" -@using System.Diagnostics +@inherits WebAssembly.PageComponents.CounterBase Counter

Counter

-

Current count: @_currentCount

-

Runtime: @_stopwatch.Elapsed.ToString("g")

+

Current count: @CurrentCount

+

Runtime: @Stopwatch.Elapsed.ToString("G")

- - -@code { - private int _currentCount = 0; - private bool _cancel; - private readonly Stopwatch _stopwatch = new(); - - private async Task Start() - { - _stopwatch.Start(); - _cancel = false; - while (!_cancel) - { - _currentCount++; - StateHasChanged(); - await Task.Delay(10); - } - _stopwatch.Stop(); - } - - private void Stop() - { - _cancel = true; - } - - private void Reset() - { - _cancel = true; - _currentCount = 0; - _stopwatch.Reset(); - } -} + \ No newline at end of file