@@ -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 ;
@@ -89,16 +90,14 @@ public Task ListenAsync()
89
90
ListeningLoop ,
90
91
_cancellationTokenSource . Token ,
91
92
TaskCreationOptions . LongRunning ,
92
- TaskScheduler . Default ) ;
93
+ TaskScheduler . Default )
94
+ . Unwrap ( ) ; // Because ListeningLoop is an async method, we need to use Unwrap to return the inner task.
93
95
94
96
return _listenForReleaseSignalFileTask ;
95
97
}
96
98
97
- public void Dispose ( )
98
- {
99
- _lockFileStream ? . Close ( ) ;
100
- _lockFileStream = null ;
101
- }
99
+ /// <summary>Releases the resources used by this <see cref="FileSystemMainDomLock" />.</summary>
100
+ public void Dispose ( ) => Dispose ( true ) ;
102
101
103
102
public void CreateLockReleaseSignalFile ( ) =>
104
103
File . Open ( _releaseSignalFilePath , FileMode . OpenOrCreate , FileAccess . ReadWrite ,
@@ -108,6 +107,26 @@ public void CreateLockReleaseSignalFile() =>
108
107
public void DeleteLockReleaseSignalFile ( ) =>
109
108
File . Delete ( _releaseSignalFilePath ) ;
110
109
110
+ /// <summary>Releases the resources used by this <see cref="FileSystemMainDomLock" />.</summary>
111
+ /// <param name="disposing">true to release both managed resources.</param>
112
+ protected virtual void Dispose ( bool disposing )
113
+ {
114
+ if ( disposing && ! _disposed )
115
+ {
116
+ _logger . LogDebug ( $ "{ nameof ( FileSystemMainDomLock ) } Disposing...") ;
117
+ _cancellationTokenSource . Cancel ( ) ;
118
+ _cancellationTokenSource . Dispose ( ) ;
119
+ ReleaseLock ( ) ;
120
+ _disposed = true ;
121
+ }
122
+ }
123
+
124
+ private void ReleaseLock ( )
125
+ {
126
+ _lockFileStream ? . Close ( ) ;
127
+ _lockFileStream = null ;
128
+ }
129
+
111
130
private async Task ListeningLoop ( )
112
131
{
113
132
while ( true )
@@ -118,6 +137,7 @@ private async Task ListeningLoop()
118
137
{
119
138
_logger . LogDebug ( "ListenAsync Task canceled, exiting loop" ) ;
120
139
}
140
+
121
141
return ;
122
142
}
123
143
@@ -127,12 +147,12 @@ private async Task ListeningLoop()
127
147
{
128
148
_logger . LogDebug ( "Found lock release signal file, releasing lock on {lockFilePath}" , _lockFilePath ) ;
129
149
}
130
- _lockFileStream ? . Close ( ) ;
131
- _lockFileStream = null ;
150
+
151
+ ReleaseLock ( ) ;
132
152
break ;
133
153
}
134
154
135
- await Task . Delay ( _globalSettings . CurrentValue . MainDomReleaseSignalPollingInterval ) ;
155
+ await Task . Delay ( _globalSettings . CurrentValue . MainDomReleaseSignalPollingInterval , _cancellationTokenSource . Token ) ;
136
156
}
137
157
}
138
158
}
0 commit comments