title: Is there a way to stop a Directory.GetFiles search
body: <p>I'm using <code>Directory.GetFiles()</code> to search files in a multi-folder directory and some of these folders are too big so the search could take up to 60 seconds. In the code below a search starts a second after the user stops typing, this works great when the user types the file name and does not pauses while typing it but if he/she pauses in the middle of the word the search will start and will not stop until it finishes even if he/she starts typing again.</p>
  
  <p>What I would like to do is stop searches while the user is typing, possibly in the inputFileName_TextChanged method.</p>
  
  <p>Is there a way to stop a search that has been already started when using <code>Directory.GetFiles</code>?</p>
  
  <pre><code>using System.Timers;
  using System.IO;
  
  namespace findFileTest
  {
  
      public partial class MainWindow : Window
      {
          Timer timer = new Timer();
  
          public MainWindow()
          {
              InitializeComponent();
  
              timer.Elapsed += new ElapsedEventHandler(TimerEvent);
              timer.Interval = 1000;
              timer.Enabled = true;
              timer.Stop();
          }
  
          private void inputFileName_TextChanged(object sender, TextChangedEventArgs e)
          {
              // How to stop the search currently in process here
              timer.Stop();
              timer.Start();
          }
  
          public void TimerEvent(object source, ElapsedEventArgs e)
          {
              timer.Stop();
              findFile();
          }
  
          private void findFile()
          {
              string fName = "";
  
              this.Dispatcher.Invoke(() =&gt; {
                  fName = inputFileName.Text;
              });
  
              var fType = ".txt";
              var fileName = fName.Trim() + fType;
  
              var file = Directory.GetFiles(@"C:\TestFolder\", fileName, SearchOption.AllDirectories).FirstOrDefault();
              if (file == null) {
                  Console.WriteLine("File not found");
              }
              else {
                  Console.WriteLine("Found:" + file);
              }
          }
      }
  }
  </code></pre>