Visual Basic.NET Language Enhancements: Free Threading
Author: Intelligent Solutions Inc.
Version Compatibility: Visual Basic.NET
Instructions: Copy the declarations and code below and paste directly into your VB project.
Threading is a complex topic, and issues such as what a thread is and the difference between single, apartment, and free threading are beyond the scope of this article.
Instead, I will just say that, in Visual Basic 6.0, code is synchronous. That means each line must finish executing before the next line begins. So, for instance, if you call a function in a class object, that function must return before any successive code can execute.
Because Visual Basic.NET will allow free-threading, this limitation will be removed. With free-threading, you will be able to spawn a thread which performs a complex or long-running task, while the rest of your application continues.
As a simple example, consider an application that imports two different long text files into two different data sources. Though you can do this asynchronously today via techniques such as callbacks, most developers would likely write code that imports the first file and, after the first import is through, imports the second.
With free-threading, you will be able to start a background process for the first import while the rest of your application can continue with the second. Imagine that you have a class for the first import called clsFirstImport:
Class clsFirstImport Sub DoImport() 'import the first file into the 'first data source End Sub End Class
The caller of an object instance of this class can implement free-threading with something like this:
Dim oImport as clsFirstImport Dim oThread As Thread Set oImport = New clsFirstImport Set oThread = New Thread(New ThreadStart(AddressOf oImport.DoImport)) oThread.Start 'continue with second import.
What will happen is that the first import and the second import will run in separate threads, or in more practical terms, simultaneously (you probably know that separate threads are not truly simultaneous on a single processor machine, but for practical purposes, they are simultaneous and will appear as such to the user).
If you are interested in a more detailed discussion of threading, including how to implement free-threading in VB 6.0 using API calls (and why you shouldn't), refer to this more advanced article.
The rest of the series: