Solved

Managing threads in VB .NET

Posted on 2010-08-21
14
138 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Duplicates in Aggregate Query 3 39
Clean Uninstall of VS Professional 2015 5 52
Problem to file 3 74
How do ASP.NET and MVC work together? 4 45
This article describes how to add a user-defined command button to the Windows 7 Explorer toolbar.  In the previous article (http://www.experts-exchange.com/A_2172.html), we saw how to put the Delete button back there where it belongs.  "Delete" is …
For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
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…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

808 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