Skip to content

Commit 66ab363

Browse files
committed
refactor: 优化性能
1 parent 56a3137 commit 66ab363

File tree

1 file changed

+11
-28
lines changed

1 file changed

+11
-28
lines changed

src/BootstrapBlazor/Components/Timer/Timer.razor.cs

Lines changed: 11 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@ public partial class Timer
4343

4444
private CancellationTokenSource CancelTokenSource { get; set; } = new();
4545

46-
private AutoResetEvent ResetEvent { get; } = new(false);
47-
4846
private bool Vibrate { get; set; }
4947

5048
/// <summary>
@@ -185,29 +183,23 @@ private async Task OnStart(TimeSpan val)
185183
CancelTokenSource = new CancellationTokenSource();
186184
}
187185

188-
while (!CancelTokenSource.IsCancellationRequested && CurrentTimespan > TimeSpan.Zero)
186+
while (CancelTokenSource is { IsCancellationRequested: false } && CurrentTimespan > TimeSpan.Zero)
189187
{
190188
try
191189
{
192190
await Task.Delay(1000, CancelTokenSource.Token);
193-
}
194-
catch (TaskCanceledException) { }
195-
196-
if (!CancelTokenSource.IsCancellationRequested)
197-
{
198-
CurrentTimespan = CurrentTimespan.Subtract(TimeSpan.FromSeconds(1));
199-
StateHasChanged();
200-
}
201-
202-
if (IsPause)
203-
{
204-
ResetEvent.WaitOne();
205-
AlertTime = DateTime.Now.Add(CurrentTimespan).ToString("HH:mm:ss");
206191

207-
// 重建 CancelToken
208-
CancelTokenSource.Dispose();
209-
CancelTokenSource = new CancellationTokenSource();
192+
if (IsPause)
193+
{
194+
AlertTime = DateTime.Now.Add(CurrentTimespan).ToString("HH:mm:ss");
195+
}
196+
else
197+
{
198+
CurrentTimespan = CurrentTimespan.Subtract(TimeSpan.FromSeconds(1));
199+
StateHasChanged();
200+
}
210201
}
202+
catch (TaskCanceledException) { }
211203
}
212204

213205
if (CurrentTimespan == TimeSpan.Zero)
@@ -229,14 +221,6 @@ private async Task OnStart(TimeSpan val)
229221
private void OnClickPause()
230222
{
231223
IsPause = !IsPause;
232-
if (!IsPause)
233-
{
234-
ResetEvent.Set();
235-
}
236-
else
237-
{
238-
CancelTokenSource.Cancel();
239-
}
240224
}
241225

242226
private string GetPauseText() => IsPause ? ResumeText : PauseText;
@@ -262,7 +246,6 @@ protected override async ValueTask DisposeAsync(bool disposing)
262246
CancelTokenSource.Cancel();
263247
CancelTokenSource.Dispose();
264248

265-
ResetEvent.Dispose();
266249
if (Module != null)
267250
{
268251
await Module.DisposeAsync();

0 commit comments

Comments
 (0)