C# 从VS2010运行时,应用程序仅关闭(无错误或smth)
问题是应用程序关闭时没有任何错误,VS保持打开状态。 我有多个动态创建的C# 从VS2010运行时,应用程序仅关闭(无错误或smth),c#,.net,multithreading,filesystemwatcher,C#,.net,Multithreading,Filesystemwatcher,问题是应用程序关闭时没有任何错误,VS保持打开状态。 我有多个动态创建的文件系统监视程序,它们都在“创建”事件上有eventhandler。因此,此eventhandler方法如下所示: void watcher_FileCreated(object sender, FileSystemEventArgs e) { FileInfo f1 = new FileInfo(e.FullPath); filesDataGrid.Rows.Add(f1.Name); foreac
文件系统监视程序
,它们都在“创建”事件上有eventhandler。因此,此eventhandler方法如下所示:
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
}
}
导致程序关闭的行是我向DataGridView-filesDataGrid.Rows.Add(f1.name)添加文件名的行代码>
没有那条线也可以运行。
奇怪的是,当从projects文件夹中的.exe文件启动时,应用程序运行正常。我看不到我的代码中有错误,但我想如果它甚至没有显示错误消息的话,它一定是出了问题。
和-程序可以在没有警告的情况下关闭的最常见原因是什么?用Try{}catch(Exception ex){}块包装函数。
我认为这是因为DataGridRow需要首先使用FileSystemWatcher中的变量创建
e、 g
FileSystemWatcher
将在单独的线程中触发事件。事件处理程序中的逻辑需要考虑这一事实,并执行所需的任何同步。所以你需要这样的东西:
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
}
}
}
谢谢-我尝试了try catch,得到了“跨线程操作无效!FileDataGrid是从线程访问的,而不是在其上创建的”。现在我有了工作。但是仍然不理解为什么它是跨线程的,因为它是在使用它的同一个类中创建的,并且没有在代码中创建新线程。这通常意味着您正在尝试在它试图监视更改的同一个线程上更新DataGrid。因此,我会将另一个类似UpdateDataGrid的事件处理程序变大,并将参数传递给它,我猜如果fl.Name在thred上。所以不能直接更新控件。你在使用Winforms吗?还是WPF?等等,是Winforms。我想我会尝试eventhandler向DataGrid添加信息。我想应该可以。谢谢-这就解释了交叉线程错误。但我能在eventhandler方法中以某种方式更新表吗?@andree-参见我的示例。您需要调用回GUI线程来更新它。这很有效。我应该检查“Invoke”方法以便更好地理解。
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
}
}
}