Solved

Managing threads in VB .NET

Posted on 2010-08-21
14
136 Views
Last Modified: 2014-02-22
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
Comment
Question by:FINDERSOL
  • 12
14 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 33494314
>>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
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 33496222
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
 

Author Comment

by:FINDERSOL
ID: 39879848
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879849
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
 

Author Comment

by:FINDERSOL
ID: 39879850
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879851
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879852
Happy with proposed answer
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:FINDERSOL
ID: 39879853
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879854
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879855
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879856
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879857
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879858
Happy with proposed answer
0
 

Author Comment

by:FINDERSOL
ID: 39879860
Happy with proposed answer
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

In this article, I will show how to use the Ribbon IDs Tool Window to assign the built-in Office icons to a ribbon button.  This tool will help us to find the OfficeImageId that corresponds to our desired built-in Office icon. The tool is part of…
With most software applications trying to cater to multiple user needs nowadays, the focus is to make them as configurable as possible. For e.g., when creating Silverlight applications which will connect to WCF services, the service end point usuall…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now