0

I am building a program that is supposed to watch some project folder for change in source code and then send these changes somewhere and in the process, log the files that were changed in a Windows Form TextBox.

The code looks something like this:

void Form_Load(object sender, EventArgs e)
{
    FileSystemWatcher fsw = new FileSystemWatcher("C:\\test");
    fsw.Created += File_Created;
}

void File_Created(object sender, FileSystemEventArgs e)
{
    string name = Path.GetFileName(e.FullPath);
    logs.Text += name + Environment.NewLine;
}

Of course, this is not the actual code but it's enough to see the point. Every time the File_Created event is triggered, it creates a new thread and thus I'm unable to interact with the UI from that event, it throws an exception.

Everything else in my program works except the logging part but it's kinda annoying.

Is there a way around it?

Thanks, Arik

areller
  • 4,800
  • 9
  • 29
  • 57
  • 1
    Possible duplicate of [How to update the GUI from another thread in C#?](http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c) – user700390 Jan 15 '16 at 23:15
  • 1
    Use Invoke / BeginInvoke. Try searching as this has been asked and answered many times. – user700390 Jan 15 '16 at 23:15

1 Answers1

1

If you want to update your UI from other thread you need to use:

Dispatcher.Invoke(new Action(() =>
{
   logs.Text += name + Environment.NewLine; 
}));

I hope this can help you

ganchito55
  • 3,559
  • 4
  • 25
  • 46