Skip to content

Commit a7a8fea

Browse files
authored
Merge pull request #6 from PhantomGamers/fix-restart
Create new CancellationTokenSource on Start()
2 parents 826c46d + 92f277c commit a7a8fea

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

Source/FileWatcherEx/FileSystemWatcherEx.cs

+10-11
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public class FileSystemWatcherEx : IDisposable
2121
private FileSystemWatcher? _fsw;
2222

2323
// Define the cancellation token.
24-
private readonly CancellationTokenSource _cancelSource = new();
24+
private CancellationTokenSource? _cancelSource;
2525

2626
#endregion
2727

@@ -231,6 +231,7 @@ void InvokeRenamedEvent(object? sender, FileChangedEvent fileEvent)
231231
Console.WriteLine(string.Format("{0} | {1}", Enum.GetName(typeof(ChangeType), ChangeType.LOG), log));
232232
});
233233

234+
_cancelSource = new();
234235
_thread = new Thread(() => Thread_DoingWork(_cancelSource.Token))
235236
{
236237
// this ensures the thread does not block the process from terminating!
@@ -284,15 +285,14 @@ public void Stop()
284285
if (_fsw != null)
285286
{
286287
_fsw.EnableRaisingEvents = false;
288+
_fsw.Dispose();
287289
}
288290

289-
if (_watcher != null)
290-
{
291-
_watcher.Dispose();
292-
}
291+
_watcher?.Dispose();
293292

294293
// stop the thread
295-
_cancelSource.Cancel();
294+
_cancelSource?.Cancel();
295+
_cancelSource?.Dispose();
296296
}
297297

298298

@@ -301,11 +301,10 @@ public void Stop()
301301
/// </summary>
302302
public void Dispose()
303303
{
304-
if (_fsw != null)
305-
{
306-
_fsw.Dispose();
307-
GC.SuppressFinalize(this);
308-
}
304+
_fsw?.Dispose();
305+
_watcher?.Dispose();
306+
_cancelSource?.Dispose();
307+
GC.SuppressFinalize(this);
309308
}
310309

311310

0 commit comments

Comments
 (0)