?
Solved

Managing threads in VB .NET

Posted on 2010-08-21
14
Medium Priority
?
153 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 86

Accepted Solution

by:
Mike Tomlinson earned 1500 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

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
 

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

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

zlib is a free compression library (a DLL) on which the popular gzip utility is built.  In this article, we'll see how to use the zlib functions to compress and decompress data in memory; that is, without needing to use a temporary file.  We'll be c…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
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…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

765 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