Library tutorials & articles

Multithreading in VB.NET

Introduction

Multithreading, a very powerful technique, is essential for modern software development.  Software users expect to work with a very responsive program that they don’t have to wait on, which is a very reasonable demand with the processor speeds that are currently available.  Enter multithreading.  Multithreading is the concept of having several different paths of code running at the same time.

When you introduce multithreading in your applications, you immediately make programming more complicated and add design time.  You must know exactly what your application and all its threads are doing at all times.  You have to account for deadlocks, race conditions and corrupting variable values.  In this article we will examine the different methods in Visual Basic.Net to accomplish thread synchronization.  We will learn what deadlocks and race conditions are and how to avoid these common problems with multithreading.

System Requirements

I will assume that you already have knowledge of basic threading in Visual Basic.Net.  You should know how to create threads and know how to do basic threading operations like Join and Sleep.  A copy of Visual Studio.Net is required to run the code samples and see the output. The code was written with Visual Studio.Net using version 1.0 of the .Net Framework with service pack 2.

Case Study Structure

This case study has three main parts.  Multithreading requires a technique called synchronization to eliminate the problems described above so we will first take a brief look at what synchronization is.  Then an in-depth look at all methods available in Visual Basic.Net for synchronization will be presented where you will learn how to correctly synchronize a multithreaded application.  After this, a look at Window’s Form synchronization and threading apartment styles will show the differences a programmer must handle between standard synchronization and visual GUI synchronization.

Comments

  1. 10 Jul 2009 at 05:08

    I need to lock the Log file once someone is using it and second person shouldn't able to write in log file. The code is shown below :

    Imports System Imports System.IO

    Module FileTransfer

    Sub Main()
        Dim dtStart As Date = Now(), dtEnd As Date = Now()
        Dim intNoofFiles As Integer = 0
        Dim strLogFileName As String = "C:\Log\FileTransferLog_" + dtStart.Year.ToString().PadLeft(4, "0") + dtStart.Month.ToString().PadLeft(2, "0") + dtStart.Day.ToString().PadLeft(2, "0") + ".txt"
        Dim oWrite As StreamWriter = File.AppendText(strLogFileName)
    
    
        oWrite.WriteLine("=================================================================================================")
        oWrite.WriteLine("Starting PRESTO File Transfer Job. Start Date: " + dtStart.ToString())
        oWrite.WriteLine("=================================================================================================")
    
        ' Call main job 
        subMoveFiles("C:\Presto\Inbound\", "c:\PRESTO_FILES\", oWrite, intNoofFiles)
    
        dtEnd = Now()
        oWrite.WriteLine("=================================================================================================")
        oWrite.WriteLine("Completed PRESTO File Transfer Job. End Date: " + dtEnd.ToString())
        oWrite.WriteLine("Total number of files transferred: " + intNoofFiles.ToString())
        oWrite.WriteLine("=================================================================================================")
    
        oWrite.Close()
    End Sub
    
    Public Sub subMoveFiles(ByVal strSrcDirectory As String, ByVal strDstDirectory As String, ByRef oWrite As StreamWriter, ByRef intNoofFiles As Integer)
        If strDstDirectory(strDstDirectory.Length - 1) <> Path.DirectorySeparatorChar Then
            strDstDirectory += Path.DirectorySeparatorChar
        End If
    
        If Not Directory.Exists(strDstDirectory) Then
            Directory.CreateDirectory(strDstDirectory)
        End If
    
        Dim strFileSystemEntries As String() = Directory.GetFileSystemEntries(strSrcDirectory)
        Dim strFileSystemEntry As String = ""
        For Each strFileSystemEntry In strFileSystemEntries
            If (Directory.Exists(strFileSystemEntry)) Then
                'Sub directories
                subMoveFiles(strFileSystemEntry, strDstDirectory + Path.GetFileName(strFileSystemEntry), oWrite, intNoofFiles)
            Else
                ' get the created date / last written date
                If DateAdd(DateInterval.Minute, 5, File.GetLastWriteTime(strFileSystemEntry)) < Now() Then
                    oWrite.WriteLine("Transferring File: " + strFileSystemEntry)
                    ' First Copy the file to the destination and then Delete
                    File.Copy(strFileSystemEntry, strDstDirectory + Path.GetFileName(strFileSystemEntry), True)
                    File.Delete(strFileSystemEntry)
                    intNoofFiles = intNoofFiles + 1
                    oWrite.WriteLine("Completed Transferring File: " + strFileSystemEntry)
                End If
            End If
        Next
    End Sub
    

    End Module

  2. 31 Jul 2008 at 11:28

    Bundle of thanks to the author, it is very help full Yes
     

  3. 13 Dec 2006 at 07:35

    As somewhat of an advanced "newbie" I have read many articles on Multithreading, and am at a loss

    Do I need to have a delegate and call the delegate when I am using threading ?

     

    Lets say I have a datatable with 5 million rows and I need to iterate through each row - grab some info , process that info (translate it) and then save it somewhere else. For example insert it inot a completely different database (and maybe even RDBMS - Architectur)

    Now I currently for each row - but that takes a lot of time.

    I would like to spawn a (Flexible Number of threads) to do the row processing - Will my For each move on as each thread runs. So I start Thread(1) will the next trigger, and I have a new row and can start thread(2) and so on. Also my Subroutine, must

  4. 19 Jan 2006 at 19:33

    Yes, but I decided not to go into detail since it's a vb.net article and you can't use it

  5. 11 Jan 2006 at 08:47

    Volatility means a lot more than is described in the article. It doesn't just affect the variable which has the volatile modifed; it affects the whole memory model for sections of code involving access to that variable.


    I agree that there's no use of volatile which can't be semantically achieved using locks, and indeed I generally prefer to use locks myself. However, there is a speed difference between acquiring a lock and just using a volatile variable - in a very few cases it might be significant. I'm surprised VB.NET doesn't have any way of specifying this.


    See the volatility page of my C# threading article for more information.


    Jon Skeet

  6. 01 Jan 1999 at 00:00

    This thread is for discussions of Multithreading in VB.NET.

Leave a comment

Sign in or Join us (it's free).

John Spano John Spano cofounder and CTO of NeoTekSystems, a Greenville, South Carolina technology consulting company. NeoTekSystems offers IT consulting, custom programming, web design and web hosting. We spe...

Related discussion

Related podcasts

  • Concurrency Pt. 2

    Podcast (MP3): Download Hosts: Alexander Michael Guests: Recording venue: In this second part of our concurrency series Michael and Alexander talk about basic patterns for concurrent programming, such as Active and Monitor Object, Scoped Locking and ...

We'd love to hear what you think! Submit ideas or give us feedback