我正在开发一些代码来检测目录中的新文件,并通过FileSystemWatcher的Created事件在新线程中发出信号。在测试时我发现在从事件中删除了事件处理程序后,正在使用的线程没有关闭。这是为什么?当我删除事件处理程序时,我做错了吗?
我的代码如下所示:
Private fileSystemWatcher As FileSystemWatcher
Private fileSystemEventHandler As New FileSystemEventHandler(AddressOf UpdateSomething)
Private isStopping As Boolean
Private Sub NewThread()
fileSystemWatcher = New FileSystemWatcher("C:\Temp")
fileSystemWatcher.Filter = "*.xml"
fileSystemWatcher.IncludeSubdirectories = False
fileSystemWatcher.NotifyFilter = NotifyFilters.FileName
AddHandler fileSystemWatcher.Created, fileSystemEventHandler
fileSystemWatcher.EnableRaisingEvents = True
End Sub
Private Sub UpdateSomething(ByVal source As Object, ByVal e As FileSystemEventArgs)
Thread.CurrentThread.Name = "UpdateSomething"
Console.WriteLine(e.FullPath)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
fileSystemWatcher.EnableRaisingEvents = False
RemoveHandler fileSystemWatcher.Created, fileSystemEventHandler
fileSystemWatcher.Dispose()
fileSystemWatcher = Nothing
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim thread As New Thread(AddressOf NewThread)
thread.Name = "NewThread"
thread.Start()
End Sub
所以首先我开始点击Button 2来启动事件处理程序。我将xml文件复制到Temp文件夹,该事件将触发并设置线程的名称。之后,我将单击按钮1以删除事件处理程序。如果我暂停执行,则线程“UpdateSomething”仍将存在。有人可以解释原因吗?
答案 0 :(得分:0)
当您按下Button1时,将xml文件添加到临时文件夹时不再调用UpdateSomething。这意味着它已成功删除了事件处理程序。但是,处理程序的实例仍可以运行。删除事件处理程序仅断开函数与事件的连接。如果线程仍处于活动状态,您应该能够使用Thread.cancelJob终止它。
答案 1 :(得分:0)
旧问题,但我想我会以任何方式结束。正如@ thomas-levesque所说,这是因为ThreadPool。