@@ -15,6 +15,7 @@ internal class FileSystemMainDomLock : IMainDomLock
1515 private readonly string _lockFilePath ;
1616 private readonly ILogger < FileSystemMainDomLock > _logger ;
1717 private readonly string _releaseSignalFilePath ;
18+ private bool _disposed ;
1819 private Task ? _listenForReleaseSignalFileTask ;
1920
2021 private FileStream ? _lockFileStream ;
@@ -88,16 +89,14 @@ public Task ListenAsync()
8889 ListeningLoop ,
8990 _cancellationTokenSource . Token ,
9091 TaskCreationOptions . LongRunning ,
91- TaskScheduler . Default ) ;
92+ TaskScheduler . Default )
93+ . Unwrap ( ) ; // Because ListeningLoop is an async method, we need to use Unwrap to return the inner task.
9294
9395 return _listenForReleaseSignalFileTask ;
9496 }
9597
96- public void Dispose ( )
97- {
98- _lockFileStream ? . Close ( ) ;
99- _lockFileStream = null ;
100- }
98+ /// <summary>Releases the resources used by this <see cref="FileSystemMainDomLock" />.</summary>
99+ public void Dispose ( ) => Dispose ( true ) ;
101100
102101 public void CreateLockReleaseSignalFile ( ) =>
103102 File . Open ( _releaseSignalFilePath , FileMode . OpenOrCreate , FileAccess . ReadWrite ,
@@ -107,7 +106,27 @@ public void CreateLockReleaseSignalFile() =>
107106 public void DeleteLockReleaseSignalFile ( ) =>
108107 File . Delete ( _releaseSignalFilePath ) ;
109108
110- private void ListeningLoop ( )
109+ /// <summary>Releases the resources used by this <see cref="FileSystemMainDomLock" />.</summary>
110+ /// <param name="disposing">true to release both managed resources.</param>
111+ protected virtual void Dispose ( bool disposing )
112+ {
113+ if ( disposing && ! _disposed )
114+ {
115+ _logger . LogInformation ( $ "{ nameof ( FileSystemMainDomLock ) } Disposing...") ;
116+ _cancellationTokenSource . Cancel ( ) ;
117+ _cancellationTokenSource . Dispose ( ) ;
118+ ReleaseLock ( ) ;
119+ _disposed = true ;
120+ }
121+ }
122+
123+ private void ReleaseLock ( )
124+ {
125+ _lockFileStream ? . Close ( ) ;
126+ _lockFileStream = null ;
127+ }
128+
129+ private async Task ListeningLoop ( )
111130 {
112131 while ( true )
113132 {
@@ -126,12 +145,12 @@ private void ListeningLoop()
126145 {
127146 _logger . LogDebug ( "Found lock release signal file, releasing lock on {lockFilePath}" , _lockFilePath ) ;
128147 }
129- _lockFileStream ? . Close ( ) ;
130- _lockFileStream = null ;
148+
149+ ReleaseLock ( ) ;
131150 break ;
132151 }
133152
134- Thread . Sleep ( _globalSettings . CurrentValue . MainDomReleaseSignalPollingInterval ) ;
153+ await Task . Delay ( _globalSettings . CurrentValue . MainDomReleaseSignalPollingInterval , _cancellationTokenSource . Token ) ;
135154 }
136155 }
137156}
0 commit comments