Library tutorials & articles

Multithreading in VB.NET

Volatile Keyword & Conclusion

A Quick Word on the volatile Keyword

In your reading or study of .NET code, the volatile C# keyword might come up. This keyword does not exist in Visual Basic. Don’t worry though; it doesn’t add any functionality to C# that can’t be done with the other synchronization objects discussed in this case study.

The volatile keyword tells the compiler that the variable it references could change at anytime and that no optimizations should be done to it. It will prohibit the compiler from storing the variable in a register and force it read it new from memory each time.

Variables marked as volatile aren’t necessarily thread safe. They only insure that each read of the variable is the latest information. To see what a declaration looks like look at the following code snip-it, which declares an Integer variable as volatile.

private volatile int MyInteger;

Use of Monitor is a much safer and better way to handle synchronization. It guarantees that the variable is up to date as only one thread is accessing the variable at a time. It is safe to replace volatile variable access with Monitor blocks of code or any other synchronization method discussed in the case study that fit your needs. Good synchronization practice will eliminate the need for volatile.

Summary

Multithreaded applications are a must today.The Dot Net Framework makes creating these applications much easier than traditional programming methods. Be sure to take advantage of multithreading and of all available methods of synchronization.

When designing for multithreaded applications remember the age-old proverb: An ounce of prevention is worth a pound of cure. It is much easier to prevent deadlocks and other multithreaded bugs by taking a few extra minutes and trying to prevent them. You will usually spend a lot of time trying to find the cause of these bugs when reported from the field, as they don’t usually show up stepping through code, but only when running at full speed.

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 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