Skip to content

Commit 89d5155

Browse files
committed
refactor: improve auto fetch timer implementation using PeriodicTimer
sourcegit-scm#792 sourcegit-scm#1121 Replace System.Threading.Timer with PeriodicTimer for auto fetch functionality to: - Handle cancellation gracefully during repository close - Avoid unhandled exceptions in timer callbacks
1 parent 55be1ad commit 89d5155

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

src/ViewModels/Repository.cs

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -456,12 +456,13 @@ public void Open()
456456
_selectedView = _histories;
457457
_selectedViewIndex = 0;
458458

459-
_autoFetchTimer = new Timer(AutoFetchImpl, null, 5000, 5000);
459+
_ = StartAutoFetchAsync();
460460
RefreshAll();
461461
}
462462

463463
public void Close()
464464
{
465+
_isClosing = true;
465466
SelectedView = null; // Do NOT modify. Used to remove exists widgets for GC.Collect
466467

467468
var settingsSerialized = JsonSerializer.Serialize(_settings, JsonCodeGen.Default.RepositorySettings);
@@ -473,7 +474,7 @@ public void Close()
473474
{
474475
// Ignore
475476
}
476-
_autoFetchTimer.Dispose();
477+
_autoFetchTimer?.Dispose();
477478
_autoFetchTimer = null;
478479

479480
_settings = null;
@@ -2511,7 +2512,34 @@ private void CalcMatchedFilesForSearching()
25112512
MatchedFilesForSearching = matched;
25122513
}
25132514

2514-
private void AutoFetchImpl(object sender)
2515+
private async Task StartAutoFetchAsync()
2516+
{
2517+
_autoFetchTimer = new PeriodicTimer(TimeSpan.FromSeconds(5));
2518+
2519+
try
2520+
{
2521+
while (!_isClosing && await _autoFetchTimer.WaitForNextTickAsync())
2522+
{
2523+
if (_isClosing)
2524+
break;
2525+
2526+
try
2527+
{
2528+
await Task.Run(AutoFetchImpl);
2529+
}
2530+
catch (Exception)
2531+
{
2532+
// ignored
2533+
}
2534+
}
2535+
}
2536+
catch (OperationCanceledException)
2537+
{
2538+
// ignored
2539+
}
2540+
}
2541+
2542+
private void AutoFetchImpl()
25152543
{
25162544
if (!_settings.EnableAutoFetch || _isAutoFetching)
25172545
return;
@@ -2579,7 +2607,8 @@ private void AutoFetchImpl(object sender)
25792607
private List<Models.Submodule> _visibleSubmodules = new List<Models.Submodule>();
25802608

25812609
private bool _isAutoFetching = false;
2582-
private Timer _autoFetchTimer = null;
2610+
private PeriodicTimer _autoFetchTimer;
2611+
private volatile bool _isClosing = false;
25832612
private DateTime _lastFetchTime = DateTime.MinValue;
25842613
}
25852614
}

0 commit comments

Comments
 (0)