开发者

Thread is not being removed when removing event handler in VB.NET

I'm developing some code to detect new files in a directory and signal it in a new thread through the Created event of FileSystemWatcher. While testing this I noticed that after I removed the eventhandler from the event the thread that was being used was not closed. Why is that? Am I doing something wrong when I'm remo开发者_如何转开发ving the eventhandler?

My code looks like this:

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

So first I start off clicking Button 2 to start the event handler. I copy a xml file to the Temp folder and the event will trigger and set the name of the thread. After that I will click Button 1 to remove the event handler. If I then pause the execution the Thread "UpdateSomething" will still be there. Can someone explain why?


When you press Button1, UpdateSomething is no longer called when you add an xml file to the temp folder. That means it has succesfully removed the event handler. However, an instance of the handler could still be running. Removing an event handler only disconnects the function from the event. If the thread is still active, you should be able to terminate it using Thread.cancelJob.


Old question but I thought I will close it any way. As @thomas-levesque wrote it’s because of the ThreadPool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜