Results 1 to 9 of 9

Thread: Creating a new thread

  1. #1

    Thread Starter
    Fanatic Member Emcrank's Avatar
    Join Date
    Jan 2009
    Posts
    566

    Creating a new thread

    A thread is a fork of operation within the application
    To create a new one put this at top of code under Class but not in a sub
    VB.NET Code:
    1. Private running As Boolean = True
    2. Private t As Threading.Thread
    Then put these in the correct places
    VB.NET Code:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2. t = New Threading.Thread(New Threading.ThreadStart(AddressOf threadfunc))
    3. t.IsBackground = True
    4. t.Start()
    5. End Sub
    6.  
    7. Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    8. running = False
    9. If t.IsAlive AndAlso (Not t.Join(1000)) Then
    10.      t.Abort()
    11. End If
    12. End Sub
    13.  
    14. Private Sub threadfunc()
    15. While running
    16.       'PUT YOUR CODE HERE
    17. End While
    18. End Sub

  2. #2
    Lively Member sk8er_boi's Avatar
    Join Date
    Jun 2010
    Posts
    65

    Question Re: Creating a new thread

    very nice & easy... thx for the tip

    i have 1 question though ....
    how do i re-run the thread ?
    for eg. i have inserted execution of a batch file under the thread using :

    Code:
    Private Sub threadfunc()
            While running
                Shell("c:\mymusic\list.bat", AppWinStyle.Hide, True)
                running = False
            End While
        End Sub
    batch file takes abt few seconds to run & then i dump batch file's output into a text box on my form, it works fine for the first time but then when i try to run it for the second time it says :

    "Thread is running or terminated; it cannot restart."


    here's my full code if it helps, it simply lists the contents of directory & dumps it in a textbox, i know i can do this w/o a batch file, but i just wanted to test the "threading" stuff, & i knw it's a crappy one coz i'm just a beginner in vb .net ;-)

    Code:
    Imports System.IO
    
    Public Class Form1
        Dim t = New Threading.Thread(New Threading.ThreadStart(AddressOf threadfunc))
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim fiFile As New System.IO.FileInfo("c:\mymusic\list.bat")
            fiFile.Delete()
    
            Dim objStreamWriter As StreamWriter
    
            objStreamWriter = New StreamWriter("c:\mymusic\list.bat", True)
    
            objStreamWriter.WriteLine("c:")
            objStreamWriter.WriteLine("cd\")
            'objStreamWriter.WriteLine("cd windows")
            objStreamWriter.WriteLine("dir /s > c:\mymusic\list.txt")
            objStreamWriter.Close()
            t.start()
            PictureBox1.Visible = True
            Me.Refresh()
    TWAIT:
            If running = False Then
                Dim myOutput = New StreamReader("c:\mymusic\list.txt")
                Dim sValues = myOutput.ReadToEnd
                Me.rtb1.Text = sValues
            Else
                PictureBox1.Visible = True
                Me.Refresh()
                GoTo TWAIT
            End If
            PictureBox1.Visible = False
            running = False
        End Sub
        Private running As Boolean = True
    
        
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            PictureBox1.Visible = False
        End Sub
        Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            running = False
            t.Abort()
        End Sub
        Private Sub threadfunc()
            While running
                Shell("c:\mymusic\list.bat", AppWinStyle.Hide, True)
                running = False
            End While
        End Sub
    End Class

    picturebox? = i have inserted a animated gif that is displayed till the batch file is running in back ground

  3. #3
    Pro Grammar chris128's Avatar
    Join Date
    Jun 2007
    Location
    England
    Posts
    7,604

    Re: Creating a new thread

    To re-run the thread, you need to create a new thread and start that. So instead of only creating a new instance of the thread object at class level, create a new instance in your button click event handler. Also, I would suggest that if you want the thread to end when your application ends, you dont need to call Thread.Abort in the form closing event, you can just set the thread's IsBackground property to True and it will automatically close when the application ends (unless of course this is not your main form and you just want the thread to end when this form is closed).

    So here is an example of the relevant parts of your code but adapted with both of the above suggestions:

    Code:
    Public Class Form1
        Dim t As Threading.Thread
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim fiFile As New System.IO.FileInfo("c:\mymusic\list.bat")
            fiFile.Delete()
    
            Dim objStreamWriter As StreamWriter
    
            objStreamWriter = New StreamWriter("c:\mymusic\list.bat", True)
    
            objStreamWriter.WriteLine("c:")
            objStreamWriter.WriteLine("cd\")
            'objStreamWriter.WriteLine("cd windows")
            objStreamWriter.WriteLine("dir /s > c:\mymusic\list.txt")
            objStreamWriter.Close()
            t = New Threading.Thread(New Threading.ThreadStart(AddressOf threadfunc))
            t.IsBackground = True
            t.start()
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


  4. #4
    Lively Member sk8er_boi's Avatar
    Join Date
    Jun 2010
    Posts
    65

    Question Re: Creating a new thread

    for some reason, doesn't work the problem occurs when i run it for the second time , it simply does not execute the batch file [under "shell"]

    can i do this using background worker ?

  5. #5
    Lively Member sk8er_boi's Avatar
    Join Date
    Jun 2010
    Posts
    65

    Thumbs up Re: Creating a new thread

    Quote Originally Posted by sk8er_boi View Post
    for some reason, doesn't work the problem occurs when i run it for the second time , it simply does not execute the batch file [under "shell"]

    can i do this using background worker ?
    hey ...GOT IT !

    it wasn't the thread, it was problem with my code, i didn't close the StreamReader due to which batch file cudn't write the output , works fine now

    thx all for help !

  6. #6
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Creating a new thread

    You don't have to abort the thread, which is not good if you can avoid it.
    Just call t.Join() after setting the flag to False. Or possibly:
    Code:
    If Not t.Join(1000) Then t.Abort()
    . Or you can abort it without setting the flag.

  7. #7

  8. #8
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Creating a new thread

    Again, you're testing a Boolean value against true ^^. And that wasn't what I said, either. Just put that code exactly where you have all that thread-aborting code.

  9. #9
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Creating a new thread

    To sum up:

    Code:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
         t = New Threading.Thread(New Threading.ThreadStart(AddressOf threadfunc))
         t.IsBackground = True
         t.Start()
    End Sub
    
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
         running = False
         If t.IsAlive AndAlso (Not t.Join(1000)) Then t.Abort()
    End Sub
    
    Private Sub threadfunc()
         While running
              'PUT YOUR CODE HERE
         End While
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width