VB.NET中的多線程開發
引言
對于使用VB6的開發者而言,要在程序中實現多線程(multi-thread)功能,一般就是使用Win32 API調用。但凡是進行過這種嘗試的開發者都會感覺到實現過程非常困難,而且總是會發生些null terminated strings GPF的錯誤。可是有了VB.NET,一切煩惱都成為過去。
自由線程(free threaded)
在VB6中,我們只能對組件設置多線程模式,這通常就是單元模式的多線程。對于單元線程組件而言,組件中的每個可執行方法都將在一個和組件相聯系的線程上運行。這樣,我們就可以通過創建新的組件實例,使得每個實例都有一個相應的線程單元,從而達到每個正在運行的組件都有它自己的線程,多個組件可以在各自的單元中同時運行方法。
但是如果在程序的Session或Application控制范圍內,我們不會使用單元線程組件,最佳的也是唯一的選擇是自由線程組件。可是僅僅有VB6還不行,我們需要VC++或Java的幫助。
現在好了,VB.NET改善了這些功能,.NET SDK中包含的System.Threading名字空間專門負責實現多線程功能,而且操作相當簡單:只需要利用System.Threading名字空間中的Thread類,就具有了實現自由線程的屬性和方法。
一個創建自由線程的例子解析
我們來看看下面的VB.NET代碼,它演示了實現自由線程的過程:
| Imports System ' Import the threading namespace Imports System.Threading Public Class clsMultiThreading ' This is a simple method that runs a loop 5 times ' This method is the one called by the HelloWorldThreadingInVB ' class, on a separate thread. Public Sub OwnThread() Dim intCounter as integer For intCounter = 1 to 5 Console.WriteLine("Inside the class: " & intCounter.ToString()) Next End Sub End Class Public Class HelloWorldThreadingInVB ' This method is executed when this EXE is run Public Shared Sub Main() Dim intCounter as integer ' Declare an instance of the class clsMultithreading object Dim objMT as clsMultiThreading = new clsMultiThreading() ' Declare an instance of the Thread object. This class ' resides in the System.Threading namespace Dim objNewThread as Thread 'Create a New Thread with the Thread Class and pass ' the address of OwnThread method of clsMultiThreading class objNewThread = new Thread(new ThreadStart(AddressOf objMT.OwnThread)) ' Start a new Thread. This basically calls the OwnThread ' method within the clsMultiThreading class ' It is important to know that this method is called on another ' Thread, as you will see from the output objNewThread.Start() ' Run a loop and display count For intCounter = 10 to 15 Console.WriteLine("Inside the Sub Main: " & intCounter.ToString()) Next End Sub End Class |
代碼的開始是引入名字空間System和System.Threading,然后創建一個公用類clsMultiThreading。類clsMultiThreading中包含一個公用方法OwnThread,它執行了5次for循環,每次顯示信息到屏幕。創建這個類的目的是為了以單獨線程的方式從其他類中調用OwnThread方法。
接著,我們創建另外一個類HelloWorldThreadingInVB,它包含一個方法Main。當最終生成的可執行文件運行時,Main將啟動。在方法Main中,我們創建了一個clsMultiThreading類的實例,這樣就能調用它的方法OwnThread了。
現在,我們通過傳遞方法OwnThread的地址的方式來創建線程類實例,實際上這就等于創建了一個新的線程,并且告知線程當它運行時要執行的方法。我們使用函數AddressOf 獲取方法OwnThread的地址,然后將之傳遞到ThreadStart代表類。
然后,我們調用Thread類的Start方法啟動了這個新類。新類按照自己的方式開始運行,不再需要依賴創建它的類。
編 譯
我們將上面的代碼保存為文件Thread.VB,然后將之進行編譯:
| vbc.exe Thread.vb /t:exe /debug /cls |
編譯成功后,將創建可執行文件Thread.Exe。運行Thread.Exe,我們會得到下面的結果:
![]() |
請注意:來自clsMultiThreading 類和HellWorldThreadinginVB 類的輸出信息并不是同步的。這就表明,當執行objNewThread.Start()命令的同時,一個新線程也啟動了,并且執行了那個新線程中的OwnThread方法。2個線程是并列運行的,現象就是顯示信息數字1到5不是在一起,其中穿插了來自main線程的輸出信息。
結 語
以上就是在VB.NET中創建多線程應用的過程。你會感到這是多么的簡單,但同時實現了非常強大的功能。使用多線程功能,我們可以創建更好的商業和數據層組件,并且,憑借我們的想像力,將之發揮到更好。
