0

I have the following code where I have a single TextBox which the user uses for entering a file name. What I want to happen is that when the user types the file name the search won't happen until he/she stops/pauses typing, similar to the way searches work in windows explorer, Outlook etc.

With the code below I'm getting the following error...

InvalidOperationException was unhandled by user code

An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code

Additional information: The calling thread cannot access this object because a different thread owns it.

Error points to line var fName = inputFileName.Text; in the findFile() method.

Any idea what could be wrong?

CODE:

namespace FileFinder
{
    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)
        {
            timer.Stop();
            timer.Start();
        }

        public void TimerEvent(object source, ElapsedEventArgs e)
        {
            timer.Stop();
            findFile();
        }

        private void findFile()
        {
            var fType = ".pdf";
            var fName = inputFileName.Text; // error points to this line
            var fileName = fName.Trim() + fType;

            var file = Directory.GetFiles(@"C:\SomeFolder\", fileName, SearchOption.AllDirectories).FirstOrDefault();
            if (file == null) {
                myButton.Background = Brushes.Red;
            }
            else {
                myButton.Background = Brushes.Green;
            }
        }
    }
}
fs_tigre
  • 10,650
  • 13
  • 73
  • 146
  • 1
    https://stackoverflow.com/a/17955298/284240 – Tim Schmelter Oct 20 '17 at 13:54
  • Enclosing `var fName = inputFileName.Text;` inside `this.Dispatcher.Invoke(() => { });` did the trick. Excuse my ignorance but what would be considered the Main Thread, based on my code? – fs_tigre Oct 20 '17 at 14:08

0 Answers0