VB.NET中的多線程開發(fā)
時(shí)間:2009-02-16 04:43來源:互聯(lián)網(wǎng) 作者:佚名 點(diǎn)擊:次
引言 對(duì)于使用VB6的開發(fā)者而言,要在程序中實(shí)現(xiàn)多線程(multi-thread)功能,一般就是使用Win32 API調(diào)用。但凡是進(jìn)行過這種嘗試的開發(fā)者都會(huì)感覺到實(shí)現(xiàn)過程非常困難,而且總是會(huì)發(fā)生些null terminated strings GPF的錯(cuò)誤。可是有了VB.NET,一切煩惱都成為過
引言
對(duì)于使用VB6的開發(fā)者而言,要在程序中實(shí)現(xiàn)多線程(multi-thread)功能,一般就是使用Win32 API調(diào)用。但凡是進(jìn)行過這種嘗試的開發(fā)者都會(huì)感覺到實(shí)現(xiàn)過程非常困難,而且總是會(huì)發(fā)生些null terminated strings GPF的錯(cuò)誤。可是有了VB.NET,一切煩惱都成為過去。
自由線程(free threaded)
在VB6中,我們只能對(duì)組件設(shè)置多線程模式,這通常就是單元模式的多線程。對(duì)于單元線程組件而言,組件中的每個(gè)可執(zhí)行方法都將在一個(gè)和組件相聯(lián)系的線程上運(yùn)行。這樣,我們就可以通過創(chuàng)建新的組件實(shí)例,使得每個(gè)實(shí)例都有一個(gè)相應(yīng)的線程單元,從而達(dá)到每個(gè)正在運(yùn)行的組件都有它自己的線程,多個(gè)組件可以在各自的單元中同時(shí)運(yùn)行方法。
但是如果在程序的Session或Application控制范圍內(nèi),我們不會(huì)使用單元線程組件,最佳的也是唯一的選擇是自由線程組件。可是僅僅有VB6還不行,我們需要VC++或Java的幫助。
現(xiàn)在好了,VB.NET改善了這些功能,.NET SDK中包含的System.Threading名字空間專門負(fù)責(zé)實(shí)現(xiàn)多線程功能,而且操作相當(dāng)簡(jiǎn)單:只需要利用System.Threading名字空間中的Thread類,就具有了實(shí)現(xiàn)自由線程的屬性和方法。
一個(gè)創(chuàng)建自由線程的例子解析
我們來看看下面的VB.NET代碼,它演示了實(shí)現(xiàn)自由線程的過程:
[2]
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
[1]