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

有些话、适合烂在心里 提交于 2019-12-13 14:16:53

问题


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?


回答1:


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
        }
    }
}



回答2:


Wrap your function with a Try{}catch (Exception ex) { } block. i Would think it is because DataGridRow needs to be created with the variables from the FileSystemWatcher first.

e.g

DataGridViewRow row = filesDataGrid.NewRow();

row["columnname"] = f1.name;

filesDataGrid.Rows.Add(row);


来源:https://stackoverflow.com/questions/5195086/application-just-closes-no-error-or-smth-when-run-from-vs2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!