vb.net - VB.net 2010 中文件事件监控目录出现问题

标签 vb.net visual-studio-2010

我正在尝试编写一个简单的程序来监视 VB.NET 2010 中的文件夹中的新文件,但遇到了一些麻烦。

这是我的程序的简化版本:

Imports System.IO

Public Class Main
    Public fileWatcher As FileSystemWatcher

    Sub btnGo_Click(sender As System.Object, e As System.EventArgs) Handles btnGo.Click
        '//# initialize my FileSystemWatcher to monitor a particular directory for new files
        fileWatcher = New FileSystemWatcher()
        fileWatcher.Path = thisIsAValidPath.ToString()
        fileWatcher.NotifyFilter = NotifyFilters.FileName
        AddHandler fileWatcher.Created, AddressOf fileCreated
        fileWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub fileCreated(sender As Object, e As FileSystemEventArgs)
        '//# program does not exit when I comment the line below out
        txtLatestAddedFilePath.Text = e.FullPath
        '//# e.FullPath is valid when I set a breakpoint here, but when I step into the next line, the program abruptly halts with no error code that I can see
    End Sub
End Class

如您所见,我有一个按钮,单击该按钮将初始化 FileSystemWatcher。初始化工作正常,当我将新文件放入受监视的目录中时,程序到达 fileCreated 子目录。我什至可以看到 e.FullPath 设置正确。然而,它在那之后突然退出,没有错误代码(无论如何我都看不到)。如果我注释掉 fileCreated 子中的所有内容,程序将继续按预期运行。

有什么想法可以解释为什么它会在我身上死去吗?任何帮助将不胜感激。我对 VS/VB.NET 相当陌生,所以也许我只是犯了一个愚蠢的错误。谢谢!

最佳答案

可能是跨线程操作异常。

试试这个:

Private Sub fileCreated(sender As Object, e As FileSystemEventArgs)
  me.Invoke(New MethodInvoker(Function() txtLatestAddedFilePath.Text = e.FullPath))
End Sub

或者(在您的上下文中更好),在 fileWatcher 初始化期间:

fileWatcher = New FileSystemWatcher()
fileWatcher.SynchronizingObject = me
[...]

说明:

http://www.blackwasp.co.uk/FileSystemWatcher.aspx (请参阅防止跨线程操作)

摘录:

By default, when the FileSystemWatcher object raises notification events, the delegate calls are made on a thread from the system thread pool. This will generally not be the same thread as that being used to control the form. As the demonstration application will require that the file changes be logged within a visual element of the form, using the allocated thread to modify the list box contents would result in a cross-threading operation and an IllegalOperationException being thrown.

关于vb.net - VB.net 2010 中文件事件监控目录出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4719026/

相关文章:

c# - VB.NET CType 的 C# 等价物是什么?

oracle - 通过服务器资源管理器连接到 Oracle 数据库时,如何查看除我自己的模式之外的其他模式?

c# - 如何使用 ASP.NET 和 C# 显示哪些字段仍需要填写?

c++ - 来自 2 个摄像头(用于立体视觉)的视频使用 OpenCV,但其中一个滞后

vb.net - 如何在运行时更改 iframe src?

vb.net - 如何在排序时保留 DataGridView 的编程彩色背景

vb.net - vb.net 中是否有可空的 bool 之类的东西

.net - 为什么在 Try ... Catch 中使用Finally

c++ - 从 Visual C++ 调用 Delphi DLL

c++ - 使用 floor(c++) 的向下舍入函数