Search code examples
c#.netmultithreadingfilesystemwatcher

Application just closes (no error or smth) when run from VS2010


Problem is that application closes without any error, VS stays opened. I have multiple dynamically created FileSystemWatchers, all of them have eventhandler on "Created" event. So this eventhandler method looks like this :

void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
    FileInfo f1 = new FileInfo(e.FullPath);
    filesDataGrid.Rows.Add(f1.Name);
    foreach (TLPclass table in parameterForm.getParameters)
    {
       //uses some funcion form another class
    }
}

Line which causes program to close is the one where I'm adding File name to DataGridView - filesDataGrid.Rows.Add(f1.Name); Also runs OK without that line. Weird thing is that application runs normally, when launched from .exe file in projects folder. I can't see error in my code, but I guess theres something awfully wrong with it, if it doesn't even show error message. And - what are the most common reasons why program could just shut down with no warnings?


Solution

  • The FileSystemWatcher will trigger the events in a separate thread. The logic inside the event handlers will need to take that fact in consideration and perform any synchronization needed. So you'll need something like this:

    private void watcher_FileCreated(object sender, FileSystemEventArgs e)
    {
        if (filesDataGrid.InvokeRequired)
        {
            filesDataGrid.Invoke((MethodInvoker)delegate { watcher_FileCreated(sender, e); });
        }
        else
        {
            FileInfo f1 = new FileInfo(e.FullPath);
            filesDataGrid.Rows.Add(f1.Name);
            foreach (TLPclass table in parameterForm.getParameters)
            {
               //uses some funcion form another class
            }
        }
    }