From dePoPo.net

A simple example application using threads

Posted in: General vb.NET
By dePoPo
Aug 12, 2009 - 4:43:48 PM

The code below is a simple example of how to use threads. The example is a console application, but there is no fundamental difference for a forms application.

Module Module1

    Sub Main()

        ' --- Get the first thread rolling
        Dim th1 As New Threading.Thread(AddressOf demo_thread1)  ' --- The procedure to be launched as thread
        th1.IsBackground = True                                  ' --- We want it to run in the background
        th1.Start()                                              ' --- Start the thread

        Dim th2 As New Threading.Thread(AddressOf demo_thread2)
        th2.IsBackground = True
        th2.Start()

        Console.WriteLine("main programm: i'm at the end, waiting for threads to die")

        ' --- Now we need to wait until our therads have run to completion
        While th1.IsAlive Or th2.IsAlive = True
            Console.WriteLine("main programm: There are threads alive, checking back in 3")
            System.Threading.Thread.Sleep(3000)
        End While

        ' --- Report we are done to the user, and end the programm
        Console.WriteLine("All done")
        Console.ReadLine()

    End Sub


    Public Sub demo_thread1()

        For f As Integer = 1 To 10
            Console.WriteLine("I'm Thread 1, counting 1 to 10, i'm now at " & f)
            System.Threading.Thread.Sleep(1000)
        Next

    End Sub


    Public Sub demo_thread2()

        For f As Integer = 1 To 20
            Console.WriteLine("I'm Thread 2, counting 1 to 20 at twice the speed, i'm now at " & f)
            System.Threading.Thread.Sleep(500)
        Next

    End Sub


End Module


© Copyright 2010 by dePoPo.net