Results 1 to 40 of 149

Thread: Understanding Multi-Threading in VB.Net

Threaded View

  1. #1

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Understanding Multi-Threading in VB.Net

    Some time ago I was inspired to write an article here about Lambdas and Delegates after observing a couple of posts where members voiced their misunderstanding of them. It seemed quite helpful to a couple of people and now I'm inspired yet a again to write about another troubling area in the .Net world, multi-threading. In this article I hope to be able to take someone who's only heard about it from the depths ignorance about it to being able to competently command their processor's cores to do what they were made to do, share the burden of executing one or more tasks simultaneously.

    Lets Begin

    Background

    To understand what multi-threading is you must first understand what happens when you run an executable program on an operating system. The OS loads the executable program into memory and the processor executes its code line by line. However with this simple logic one will realize that eventually the lines will run out and the program will end but when you open NotePad, it doesn't end until you tell it to so what gives ? This is because a program is basically one big loop where the same instructions keep getting executed over and over. The reality is actually far more complex that this but its the underlying idea. When you run NotePad, the program enters one big loop and which basically keeps checking for weather the user typed something or clicked a menu option and then it responds to these inputs by executing other code before returning to the loop. So if you press the letter 'K', the code leaves the loop and executes the code that is responsible to rendering the letter 'K' into NotePad's window. When this code is finished, it returns to the loop where it left off, waiting to process other messages.

    Think of the code looking like this:-
    vbnet Code:
    1. '
    2.     Public Sub Main()
    3.         Do
    4.             Dim msg As MESSAGE = GetMessage()
    5.  
    6.             If msg IsNot Nothing Then
    7.                 ProcessMessage(msg)
    8.             End If
    9.         Loop
    10.     End Sub

    The loop repeatedly checks for messages(key presses, mouse clicks etc) and when it finds one, it passes it to a procedure that knows how to take action. Its an intriguing design but what happens the action taken by ProcessMessage leads to another loop, one which will take several seconds or even minutes ? Eg. You click a hyperlink in Internet Explorer to download a file.

    Imagine that this is the code that Internet Explorer calls to download a file:-
    vbnet Code:
    1. '
    2.     Public Sub DownloadFile(ByVal url As String)
    3.  
    4.         Dim fileSize As Integer = GetFileSize(url)
    5.         Dim fileName As String = GetFileName(url)
    6.         Dim curPos As Integer = 0
    7.  
    8.         Do While curPos < fileSize
    9.             Dim fileData() As Byte
    10.  
    11.  
    12.             Dim bytesRecd As Integer = GetNextChunk(fileData)
    13.             curPos += bytesRecd
    14.  
    15.             appendToFile(fileName, fileData)
    16.         Loop
    17.  
    18.     End Sub

    Now thats not the actual code but I'd expect the concept to be similar to that, so just imagine that it is. What would happen ? Well notice that DownloadFile has a loop which repeatedly gets chucks of the file, so if this file is several gigabytes in size then this loop is going to be executing for quite a while. If clicking the download hyperlink led to that sub being executed by ProcessMessage then common sense would dictate that Internet Explorer would not be able to process any more messages until DownloadFile has finished executing and returned. This means that Internet Explorer would not respond to anything you do because the main message loop is halted. Visualize it like this:-
    vbnet Code:
    1. '
    2.     Public Sub Main()
    3.         Do
    4.             Dim msg As MESSAGE = GetMessage()
    5.  
    6.             If msg IsNot Nothing Then
    7.                 If msg.MsgType = FILEDOWNLOAD Then
    8.                     'imagine msg.Data has the url
    9.                     DownloadFile(msg.Data)
    10.                 End If
    11.             End If
    12.         Loop
    13.     End Sub
    Now I must re-iterate that this is not the actual code that does these things in Windows and IE. Its just to give you an idea of what happens.


    When DownloadFile is called the message loop cannot process additional messages until DownloadFile returns. However, we all know that we can download a file, even many files and still browse the internet. How can this be ? This is where multi-threading comes into play.

    What is multi-threading

    While many may take the fact that you can still browse while you have a file downloading in the background for granted, it is in fact multi-threading that gives you this luxury. When you have downloads in progress in Internet Explorer, these downloads are being handled by their own threads and the main browser window is running on a different thread so that each of these tasks can proceed independently. Going back to my earlier illustrations, what happens is that DownloadFile is passed off to another thread and returns immediately so the message loop can proceed as normal. Threads are exactly that, threads of execution. So what we have are two loops running at the same time. The reality though is that they are not running at the same time but Windows is actually switching between then very very quickly to give the impression of concurrency. The operating system may execute two lines of code in the message loop and switch to the download loop and execute two lines before switching back or switching to yet another thread doing something else. Note though, that on multi-core systems these two threads can actually be executing at the same time. This is what multi-threading is about, execution separate sections of code seemingly or actually at the same time. So now we come to the fun part, actually doing it which we will begin in the next post.
    Last edited by Niya; Jun 18th, 2012 at 03:09 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

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