@@ -15,6 +15,7 @@ internal class FileSystemMainDomLock : IMainDomLock
15
15
private readonly string _lockFilePath ;
16
16
private readonly ILogger < FileSystemMainDomLock > _logger ;
17
17
private readonly string _releaseSignalFilePath ;
18
+ private bool _disposed ;
18
19
private Task ? _listenForReleaseSignalFileTask ;
19
20
20
21
private FileStream ? _lockFileStream ;
@@ -88,16 +89,14 @@ public Task ListenAsync()
88
89
ListeningLoop ,
89
90
_cancellationTokenSource . Token ,
90
91
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.
92
94
93
95
return _listenForReleaseSignalFileTask ;
94
96
}
95
97
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 ) ;
101
100
102
101
public void CreateLockReleaseSignalFile ( ) =>
103
102
File . Open ( _releaseSignalFilePath , FileMode . OpenOrCreate , FileAccess . ReadWrite ,
@@ -107,7 +106,27 @@ public void CreateLockReleaseSignalFile() =>
107
106
public void DeleteLockReleaseSignalFile ( ) =>
108
107
File . Delete ( _releaseSignalFilePath ) ;
109
108
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 ( )
111
130
{
112
131
while ( true )
113
132
{
@@ -126,12 +145,12 @@ private void ListeningLoop()
126
145
{
127
146
_logger . LogDebug ( "Found lock release signal file, releasing lock on {lockFilePath}" , _lockFilePath ) ;
128
147
}
129
- _lockFileStream ? . Close ( ) ;
130
- _lockFileStream = null ;
148
+
149
+ ReleaseLock ( ) ;
131
150
break ;
132
151
}
133
152
134
- Thread . Sleep ( _globalSettings . CurrentValue . MainDomReleaseSignalPollingInterval ) ;
153
+ await Task . Delay ( _globalSettings . CurrentValue . MainDomReleaseSignalPollingInterval , _cancellationTokenSource . Token ) ;
135
154
}
136
155
}
137
156
}
0 commit comments