@@ -16,6 +16,9 @@ public class FileSystemWatcherEx : IDisposable
1616 private FileWatcher _watcher = new ( ) ;
1717 private FileSystemWatcher _fsw = new ( ) ;
1818
19+ // Define the cancellation token.
20+ private CancellationTokenSource _cancelSource = new ( ) ;
21+
1922 #endregion
2023
2124
@@ -175,22 +178,12 @@ void InvokeRenamedEvent(object sender, FileChangedEvent fileEvent)
175178 default :
176179 break ;
177180 }
178-
179-
180181 } , ( log ) =>
181182 {
182183 Console . WriteLine ( string . Format ( "{0} | {1}" , Enum . GetName ( typeof ( ChangeType ) , ChangeType . LOG ) , log ) ) ;
183184 } ) ;
184185
185-
186- _thread = new Thread ( ( ) =>
187- {
188- while ( true )
189- {
190- var e = _fileEventQueue . Take ( ) ;
191- _processor . ProcessEvent ( e ) ;
192- }
193- } )
186+ _thread = new Thread ( ( ) => Thread_DoingWork ( _cancelSource . Token ) )
194187 {
195188 // this ensures the thread does not block the process from terminating!
196189 IsBackground = true
@@ -229,6 +222,25 @@ void onError(ErrorEventArgs e)
229222 _fsw . EnableRaisingEvents = true ;
230223 }
231224
225+ private void Thread_DoingWork ( CancellationToken cancelToken )
226+ {
227+ while ( true )
228+ {
229+ if ( cancelToken . IsCancellationRequested )
230+ return ;
231+
232+ try
233+ {
234+ var e = _fileEventQueue . Take ( cancelToken ) ;
235+ _processor . ProcessEvent ( e ) ;
236+ }
237+ catch ( OperationCanceledException )
238+ {
239+ return ;
240+ }
241+ }
242+ }
243+
232244
233245 /// <summary>
234246 /// Stop watching files
@@ -245,11 +257,10 @@ public void Stop()
245257 _watcher . Dispose ( ) ;
246258 }
247259
248- if ( _thread != null )
249- {
250- _thread . Abort ( ) ;
251- }
260+ // stop the thread
261+ _cancelSource . Cancel ( ) ;
252262 }
263+
253264
254265
255266 /// <summary>
0 commit comments