@@ -57,7 +57,7 @@ public DeviceReadOnlyCollection<DeviceFullInfo> GetDevices(DataFlow type, Device
57
57
private readonly DeviceState _state ;
58
58
private readonly ILogger _context ;
59
59
private uint _threadSafeRefreshing ;
60
- private DateTime _lastRefresh = DateTime . UtcNow ;
60
+ private CancellationTokenSource _refreshCancellationTokenSource = new CancellationTokenSource ( ) ;
61
61
62
62
public bool Refreshing
63
63
{
@@ -90,20 +90,19 @@ private void DeviceChanged(object sender, DeviceChangedEventBase e)
90
90
91
91
public void Refresh ( CancellationToken cancellationToken = default )
92
92
{
93
- if ( Refreshing )
93
+ // Cancel the previous refresh operation, if any
94
+ var previousCts = Interlocked . Exchange ( ref _refreshCancellationTokenSource , CancellationTokenSource . CreateLinkedTokenSource ( cancellationToken ) ) ;
95
+ if ( previousCts != null )
94
96
{
95
- _context . Warning ( "Can't refresh, already refreshing since {LastRefresh}" , _lastRefresh ) ;
96
- //We want to be sure we get the latest refresh, it's not because we are refreshing that we'll get the latest info
97
- JobScheduler . Instance . ScheduleJob ( new DebounceRefreshJob ( _state , this , _context ) ) ;
98
-
99
- return ;
97
+ previousCts . Cancel ( ) ;
98
+ previousCts . Dispose ( ) ;
100
99
}
100
+ cancellationToken = _refreshCancellationTokenSource . Token ;
101
101
102
102
var stopWatch = Stopwatch . StartNew ( ) ;
103
103
try
104
104
{
105
105
Refreshing = true ;
106
- _lastRefresh = DateTime . UtcNow ;
107
106
var playbackDevices = new Dictionary < string , DeviceFullInfo > ( ) ;
108
107
var recordingDevices = new Dictionary < string , DeviceFullInfo > ( ) ;
109
108
@@ -164,6 +163,9 @@ public void Refresh(CancellationToken cancellationToken = default)
164
163
catch ( NullReferenceException e ) when ( ! cancellationToken . IsCancellationRequested )
165
164
{
166
165
_context . Error ( e , "Can't refresh the devices" ) ;
166
+ } catch ( NullReferenceException e ) when ( cancellationToken . IsCancellationRequested )
167
+ {
168
+ _context . Information ( e , "Cancellation requested and enumerator is disposed, ignoring" ) ;
167
169
}
168
170
}
169
171
finally
@@ -181,6 +183,8 @@ public void Dispose()
181
183
{
182
184
device . Dispose ( ) ;
183
185
}
186
+
187
+ _refreshCancellationTokenSource . Dispose ( ) ;
184
188
}
185
189
}
186
190
}
0 commit comments