Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Managing threads in VB .NET

Posted on 2010-08-21
14
Medium Priority
?
159 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:Meir Rivkin
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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article surveys and compares options for encoding and decoding base64 data.  It includes source code in C++ as well as examples of how to use standard Windows API functions for these tasks. We'll look at the algorithms — how encoding and decodi…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and 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…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

618 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