Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 161
  • Last Modified:

Managing threads in VB .NET

Can someone tell me how to close down threads in VB .NET.  The attached code was lifted off the NET and uses a thread to implement a background timer to check if a file has already been processed by the FileSyemWatcher object  I think when running each tiime a new thread is created it  never closed down.

What I require is the thread to be closed when no longer required.  Can someone please tell me how to close down the thread or is this automatically handled by the .NET engine when the class is closed down.

My question does the line

AccessTimerThread = New Thread(AddressOf AccessEntryRemovalTimer)

create a new thread each time it executed?

If this is the case then the code needs some cleanup to remove threads as they are no longer required


Thanks in anticipation
mports System.IO
Imports System.Threading
Public Class Form1
    Private Const MILLISECONDS_TO_WAIT As Integer = 100
    Private fw As FileSystemWatcher
    Private Shared AccessEntries As List(Of String)
    Private Delegate Sub UpdateBoxDelegate(ByVal msg As String)
    Private Sub UpdateBox(ByVal msg As String)
        If tbMonitor.InvokeRequired Then
            Invoke(New UpdateBoxDelegate(AddressOf UpdateBox), New Object() {msg})
        Else
            tbMonitor.AppendText(msg + vbCrLf)
        End If
    End Sub

    Private Sub AccessEntryRemovalTimer(ByVal RawFileName As Object)
        UpdateBox("Sleeping to watch for " + RawFileName.ToString + " on thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
        Thread.Sleep(MILLISECONDS_TO_WAIT)
        AccessEntries.Remove(RawFileName.ToString)
        UpdateBox("Removed " + RawFileName.ToString + " in thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
    End Sub

    Private Sub Changed(ByVal source As Object, ByVal e As FileSystemEventArgs)
        If AccessEntries.Contains(e.Name) Then
            UpdateBox("Ignoring a " + e.ChangeType.ToString + " notification for " + e.Name + " in thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
            Return
        End If
        Dim AccessTimerThread As Thread

        AccessEntries.Add(e.Name)
        UpdateBox("Adding " + e.Name + " to the collection and starting the watch thread.")
        AccessTimerThread = New Thread(AddressOf AccessEntryRemovalTimer)
        AccessTimerThread.IsBackground = True
        AccessTimerThread.Start(e.Name)

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        tbMonitor.ScrollBars = ScrollBars.Both
        AccessEntries = New List(Of String)
        fw = New FileSystemWatcher
        fw.Path = "C:\temp"
        fw.NotifyFilter = NotifyFilters.LastWrite Or NotifyFilters.LastAccess Or NotifyFilters.FileName
        AddHandler fw.Changed, AddressOf Changed
        AddHandler fw.Created, AddressOf Changed
        'AddHandler fw.Renamed, AddressOf Changed
        fw.EnableRaisingEvents = True
    End Sub

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        fw.EnableRaisingEvents = False
        RemoveHandler fw.Changed, AddressOf Changed
        RemoveHandler fw.Created, AddressOf Changed
        'RemoveHandler fw.Renamed, AddressOf Changed
        fw.Dispose()
    End Sub

    Private Sub cmdList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdList.Click
        Dim obj As Object
        tbList.Clear()
        For Each obj In AccessEntries
            tbList.AppendText(obj.ToString)
        Next
    End Sub
End Class

Open in new window

0
FINDERSOL
Asked:
FINDERSOL
  • 12
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
>>create a new thread each time it executed?

yes it is.

>>If this is the case then the code needs some cleanup to remove threads as they are no longer required

when are they no longer required?
is it possible to abort those threads without harming valuable data?
if yes, then u can add created threads in a list (or any other datastructure) and on cleanup, check the thread status and if not Aborted/Stopped, then run thread.Abort.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Those threads will automatically close and be disposed of when the code in AccessEntryRemovalTimer() is complete.

The in AccessEntryRemovalTimer() is:

    Private Sub AccessEntryRemovalTimer(ByVal RawFileName As Object)
        UpdateBox("Sleeping to watch for " + RawFileName.ToString + " on thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
        Thread.Sleep(MILLISECONDS_TO_WAIT)
        AccessEntries.Remove(RawFileName.ToString)
        UpdateBox("Removed " + RawFileName.ToString + " in thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
    End Sub

So the new thread is going to update the status, sleep for a MERE 100 milliseconds, remove the file from a list and then update the status again.

When the thread reaches the last line in the method it will automatically be disposed of....
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
FINDERSOLAuthor Commented:
Question

    View Solution
    Ask A New Question

Managing threads in VB .NET
Asked by: FINDERSOLSolved by: Mike Tomlinson
Can someone tell me how to close down threads in VB .NET.  The attached code was lifted off the NET and uses a thread to implement a background timer to check if a file has already been processed by the FileSyemWatcher object  I think when running each tiime a new thread is created it  never closed down.

What I require is the thread to be closed when no longer required.  Can someone please tell me how to close down the thread or is this automatically handled by the .NET engine when the class is closed down.

My question does the line

AccessTimerThread = New Thread(AddressOf AccessEntryRemovalTimer)

create a new thread each time it executed?

If this is the case then the code needs some cleanup to remove threads as they are no longer required


Thanks in anticipation

mports System.IO
Imports System.Threading
Public Class Form1
    Private Const MILLISECONDS_TO_WAIT As Integer = 100
    Private fw As FileSystemWatcher
    Private Shared AccessEntries As List(Of String)
    Private Delegate Sub UpdateBoxDelegate(ByVal msg As String)
    Private Sub UpdateBox(ByVal msg As String)
        If tbMonitor.InvokeRequired Then
            Invoke(New UpdateBoxDelegate(AddressOf UpdateBox), New Object() {msg})
        Else
            tbMonitor.AppendText(msg + vbCrLf)
        End If
    End Sub

    Private Sub AccessEntryRemovalTimer(ByVal RawFileName As Object)
        UpdateBox("Sleeping to watch for " + RawFileName.ToString + " on thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
        Thread.Sleep(MILLISECONDS_TO_WAIT)
        AccessEntries.Remove(RawFileName.ToString)
        UpdateBox("Removed " + RawFileName.ToString + " in thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
    End Sub

    Private Sub Changed(ByVal source As Object, ByVal e As FileSystemEventArgs)
        If AccessEntries.Contains(e.Name) Then
            UpdateBox("Ignoring a " + e.ChangeType.ToString + " notification for " + e.Name + " in thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
            Return
        End If
        Dim AccessTimerThread As Thread

        AccessEntries.Add(e.Name)
        UpdateBox("Adding " + e.Name + " to the collection and starting the watch thread.")
        AccessTimerThread = New Thread(AddressOf AccessEntryRemovalTimer)
        AccessTimerThread.IsBackground = True
        AccessTimerThread.Start(e.Name)

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        tbMonitor.ScrollBars = ScrollBars.Both
        AccessEntries = New List(Of String)
        fw = New FileSystemWatcher
        fw.Path = "C:\temp"
        fw.NotifyFilter = NotifyFilters.LastWrite Or NotifyFilters.LastAccess Or NotifyFilters.FileName
        AddHandler fw.Changed, AddressOf Changed
        AddHandler fw.Created, AddressOf Changed
        'AddHandler fw.Renamed, AddressOf Changed
        fw.EnableRaisingEvents = True
    End Sub

    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        fw.EnableRaisingEvents = False
        RemoveHandler fw.Changed, AddressOf Changed
        RemoveHandler fw.Created, AddressOf Changed
        'RemoveHandler fw.Renamed, AddressOf Changed
        fw.Dispose()
    End Sub

    Private Sub cmdList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdList.Click
        Dim obj As Object
        tbList.Clear()
        For Each obj In AccessEntries
            tbList.AppendText(obj.ToString)
        Next
    End Sub
End Class

                                 

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:

Select allOpen in new window

    2010-08-21 at 15:15:07ID26419602
Tags
    VB THREADS
Topic
    Microsoft Development
Participating Experts
    2
Points
    500
Comments
    2

Request Attention
Answers
 

Expert Comment

by: sedgwickPosted on 2010-08-22 at 09:16:55ID: 33494314
Rank: Ace

>>create a new thread each time it executed?

yes it is.

>>If this is the case then the code needs some cleanup to remove threads as they are no longer required

when are they no longer required?
is it possible to abort those threads without harming valuable data?
if yes, then u can add created threads in a list (or any other datastructure) and on cleanup, check the thread status and if not Aborted/Stopped, then run thread.Abort.
 

Accepted Solution

by: Mike TomlinsonPosted on 2010-08-22 at 19:15:07ID: 33496222
Rank: Savant

Those threads will automatically close and be disposed of when the code in AccessEntryRemovalTimer() is complete.

The in AccessEntryRemovalTimer() is:

    Private Sub AccessEntryRemovalTimer(ByVal RawFileName As Object)
        UpdateBox("Sleeping to watch for " + RawFileName.ToString + " on thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
        Thread.Sleep(MILLISECONDS_TO_WAIT)
        AccessEntries.Remove(RawFileName.ToString)
        UpdateBox("Removed " + RawFileName.ToString + " in thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
    End Sub

So the new thread is going to update the status, sleep for a MERE 100 milliseconds, remove the file from a list and then update the status again.

When the thread reaches the last line in the method it will automatically be disposed of....

500

GOOD

Save to Personal Knowledgebase

Your Comment

by: FINDERSOLPosted on 2014-02-22 at 22:21:49ID: 39879848
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0
 
FINDERSOLAuthor Commented:
Happy with proposed answer
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now