gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:37:14 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的程序来监视 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 中的所有内容sub out,程序继续按预期运行。

关于它为什么会死在我身上的任何想法?任何帮助将不胜感激。我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com