首页 > 编程 > .NET > 正文

介绍VB.NET的线程(英文)

2024-07-10 13:01:19
字体:
来源:转载
供稿:网友
one of the most notable new features in vb.net is the ability to create threads in your application. visual c++ developers have been able to write multithreaded code for years, but achieving the same effect in vb6 was fraught with difficulty.

although this exercise uses vb.net code, there's no reason why you can't get the same results using c#.

what is a thread?
the first question we need to answer is "what is a thread?" well, put simply, a thread is like running two programs in the same process. every piece of software you've written thus far contains at least one thread - the primary application thread.

for the uninitiated, a process is effectively an instance of a running program on your computer. say you're running both microsoft word and microsoft excel. both word and excel both run in a separate process, isolated from each other. with windows 2000, there is also a collection of other programs that run in the background providing things like usb support, network connectivity, and so on. these are called "services", and each one of those runs in its own service too.

a classic example of multithreaded usage is microsoft word's spell checker. one thread (the primary application thread) allows you to enter text into your document, another thread runs constantly and watches what you type, checking for errors as you go and flagging problems with spelling.

the reason for using threads is simple - it improves the performance of your application, or rather it improves the user experience. modern computer systems are designed to do many things at once, and, to use our microsoft word example again, keeping up with whatever you're typing isn't difficult for it. in fact, word has a lot of spare processing capacity because it can work so many times faster than you or i can type. by introducing threads that can do other stuff in the background, word can take advantage of the spare capacity in your computer and make your user experience a little more pleasurable.

another example is internet explorer. whenever ie has to get a resource, such as a web page or image, from the internet, it does so in a separate thread. the upshot of this is that you don't have to wait for ie to get an entire page before it will display the page for you. for example, it can download the html that makes up the text of the page in one hit, use the primary application thread to show you what it has so far and then it can start up multiple threads to go away and download each image that's referenced on the page. you can still scroll up and down the page despite the fact that it's still busy getting the rest of the data.



so, as a .net developer, do you have to use threads? if you develop desktop applications, absolutely, because you'll easily find many ways that your ui can be improved through threads. if you develop server applications, there is scope for using threads, but not every job is appropriate.

one classic server application example is collating information from diverse data sources. imagine you build a method on an object that needs to collect responses from five or six web services dotted around the internet. each of those web services will have a certain response time, depending on how busy the server is, how far away it is (in terms of the quality of the link) and what it has to do to get the data. you cannot return from the method until you've correlated all of the responses from each of the servers.

without threading, you have to do this job sequentially, i.e. you ask the first one, wait for a response, ask the second one, wait again, and so on. with threading, you can make all the operations sequential by making all six requests at the same time, and then collate information when all the requests have been satisfied. that way, the caller has to wait for the "longest response time", rather than an aggregate of all six of the response times.



synchronization
if you're a reader who's never written multithreaded code before, you might be thinking, "this doesn't look hard at all!" well, there is a wrinkle that can make writing stable multithreaded code very difficult indeed.

as you know, windows is a multitasking operating system, which means it can do many things at once. traditionally this means that windows can run many processes at once, and indeed it can. if you're using a windows 2000 computer to read this, you have a whole slew of services running in the background, internet explorer, a mail client and perhaps more applications in the foreground. each of those individual programs represents a process.

the vast majority of multitasking operating systems operate process isolation, which is a strategy whereby processes running on the same computer are not allowed to interfere with each other. this interference can either be accidental (e.g. shoddy code), or deliberate. process isolation is achieved through preventing processes from accessing memory allocated to another process.

for example, it's not possible to write a piece of software that monitors the block of memory that internet explorer uses to store the html making up a web page. if you could, when a secure web page was downloaded, you could go away and copy the memory blocks storing that page somewhere else. windows prevents developers from writing code that reads directly from or writes directly to another processes memory.

what this means is, if you're used to a single threaded application, only one part of your program is ever trying to access memory you're using. imagine you have a class and define a member variable on it. if you want to read or change that value, no one else is going to be reading or changing that same value at the same time.

this is not the case with multithreaded software, and is where the rather heady concept of thread synchronization comes in. in effect, what you're doing is sharing memory with another "process", so if you want to change a variable, you need to make sure that no one else is using it.

locking and wait states
here's some code:

dim a as integer
a = m_myvariable
a += 1
m_myvariable = a

imagine that you have two threads trying to use this code, and that m_myvariable is set to 1 on object initialisation. what we're doing is rather than using one thread to add 2 to m_myvariable to get 3, we're using two threads, each adding 1, so we will still end up with a result of 3. we have a problem if, by the time both threads have finished executing, m_myvariable is not 3.

in this scenario, we have two threads trying to access and change m_myvariable. if both threads hit this code at the same time, both threads will get a value of 1 from m_myvariable and store it. both threads then add 1 to a, and set the result back into m_myvariable. in this scenario, when both threads have finished their work, m_myvariable is 2, so our algorithm hasn't worked.

what we need to do is synchronise access to the block of code and make sure that only one of the two threads has access to it at any one time. simply, we put a lock around the code and only allow one thread to open the lock and go through the code. any other threads trying to open the lock have to wait (we say they are "blocked") until the first thread releases the lock, in which case one of the waiting threads will be able to open it, and so on.

this kind of locking is known as a "critical section", and isn't super-efficient because you're creating bottlenecks when you don't need to. imagine this code:

dim a as integer
a = m_myvariable
msgbox("the value is " & a.tostring)

if you put a critical section lock around this code, only one thread will be able to access it at any one time. well, from our perspective, what's the harm in having both threads access it at any one time? neither thread is changing anything - they're both just trying to read a value. using a critical section in this case creates a bottleneck for no reason, and removes the advantage of using threading at all!

what we need is something called a "reader/writer lock". this kind of lock needs a little more information from you, but can reduce the effect of bottlenecks. imagine you had two threads both trying to read from m_myvariable at the same time. just like when reading files from disk we can open the file to read as many times as we like - i.e. we want synchronous access. what we do is ask each thread to open the lock for "reading".

imagine we have another thread that writes to the value. well, in this case, we need exclusive access to the block of code. we don't want anyone trying to read a value we're about to change, and we don't want anyone else to write to it either. in this case, we ask the thread to open the lock for "writing".

in both cases, if we want to "read", if someone else is "writing", we'll be blocked until the write lock is released. likewise, if we want to "write", if someone else is "writing" or "reading", we'll be blocked until all the locks have been released.

a "reader/writer lock", then, provides a more meaningful locking mechanism that will only create bottlenecks when appropriate.

although our example isn't very meaningful, you must think hard about synchronisation whenever you're using threading. in visual c++, writing code that didn't lock and block properly would oftentimes result in horrendous crashes. the good thing is that with c++, you're writing at such a low level that the crash would often point out where you'd gone wrong. in vb.net, you're working at a higher level and so the chances of crashing are smaller as vb will try and handle most problems for you. when it does this, something will "not work properly" as opposed to "explode", and you'll have to dig around harder to find the cause of the problem. finding problems caused by improper synchronisation is more difficult in vb.net, so put more thinking time in at the beginning!

an example
in this article, we're going to see an example of how to create a simple desktop application that uses threads to count the number of characters and number of words in a block of text. it will, eventually, look like this:



all of the threading functionality in .net is implemented in the system.threading namespace. specifically, the object we need to use to create a thread is the system.threading.thread object.

the point we're trying to get to is this: when the user clicks the start threads button, we want to create 16 threads. (there's no reason for choosing 16 threads - we just want to create a few threads to create a fun example. we could do this with 2 or 200 threads, although it's worth noting like a lot of windows development, there's a point where adding more threads doesn't improve our application. there's no hard and fast rule about "how many threads is the right number of threads", so if you do choose to use them, feel your way around the problem to get the best results.) eight of these threads will be handled by a class called wordcounter and will be responsible for counting the words in the text. the other will be called charcounter and will be responsible for counting the number of characters. when the user clicks stop threads, or closes the application, we want to gracefully close all of the threads.

as both of these classes have a lot in common (they both need access to a block of text, they both need a way of reporting the results to the user and they both need to be controlled from the primary application thread), we're going to create a separate class called myworkthread and derive wordcounter and charcounter from this.

the other important thing about this is that we only want to create each thread once. creating threads has an amount of overhead and so we want to do it as rarely as possible. (.net does support thread pooling, but that's beyond the scope of this discussion.)

whenever a thread is being blocked, it drops into a super-efficient wait state. this means it has virtually no effect on processor usage at all - to all intents and purposes it doesn't exist. so, we can have as many threads as we like, without compromising the performance of the computer. (this is an over simplification, but is roughly correct.)

as our text won't be changing constantly (or, if it is, we can actually process the text faster than the user can type), we don't want our threads to be running all the time. we want them to spend most of their life asleep, and wake up to do their job on demand. we'll be building functionality into our base myworkthread class to do this.

creating the project
to create the project, open vs.net and start a new visual basic- windows application project. our example here is called desktopdemo, and you might care to use that name to keep things consistent.

creating the form
as you can see from our earlier screenshot, we're going to create a grid of text box controls that reports the status of each of the threads. you might have guessed that we're going to create a control array to handle this. however, when i was building this application, i couldn't work out how to create a control array using the vb.net designer, so i ended up writing code that programmatically created controls on the form. i decided to stick with this method in this exercise, as i figured a discussion on dynamic control creation might be quite useful.

to kick off, here is the form as it stands without the extra controls. the controls are named txttext, cmdstartthreads and cmdstopthreads.



our first job is to add a member variable to the form that will hold an array of the controls:

public class form1
inherits system.winforms.form

' create somewhere to keep track of all the threads...
const numthreads as integer = 16
dim m_threadoutputs(numthreads) as textbox

as you can see, we're using a constant called numthreads to hold the number of threads. an interesting point is, thanks to our method of creating the text boxes on the fly, changing this value will automatically change the ui, which is neat.

to build the basic form, vb calls a function called initializecomponent. this creates the four basic controls on our form, and defines the size and position of the form. (to see this method, expand the windows form designer generated code region contained within the class.)

after initializecomponent has returned, we can create our dynamic controls. our first job is to look at the design of the form and use that to estimate where the other forms go. specifically, we're going to use the gap between the text box and the buttons as a metric to determine where the rest of the controls go. add this code:

public sub new()

mybase.new()

form1 = me

'this call is required by the win form designer.
initializecomponent()

'todo: add any initialization after the initializecomponent() call



' work out the distance between the bottom of the text box, and the top
' of the startthreading button...
dim margin as integer
margin = cmdstartthreads.bounds.top - txttext.bounds.bottom


good news for vb6 desktop developers: in vb.net, the crazy twip has been dumped and we now use pixels. this means we no longer have to mess around with converting twips to pixels and back again.

after we have the margin, we need to work out the y-coordinate of the first dynamic control:

' then, start out new controls at the bottom of the start button, plus a
' small border...
dim y as integer = cmdstartthreads.bounds.bottom + (margin * 4)

after this, we need to work out how wide our controls should be. we want two columns, so we need to base this on the width of the form, and use our margin value to space everything properly.

' next, work out how wide the form is...
dim width as integer = form1.bounds.width

' then, work out the mid point of the form, and the width of
' any controls, given you want 2x margin on both sides...
dim midpoint as integer = (width / 2).toint32
dim controlwidth as integer = midpoint - (margin * 4)
dim controlheight as integer = 20

once we have the metrics, we can start looping and creating the textbox controls. we'll also put a default value in the box indicating the id of the thread that will be using it:

' create an array of text box controls...
dim n as integer
for n = 0 to numthreads - 1

' create a new object...
m_threadoutputs(n) = new textbox()
m_threadoutputs(n).text = "thread #" & n.tostring

next we need to work out whether to put the control on the left or on the right. we use mod to determine if n is even or odd.

' work out where to put it... even numbered controls go
' on the left, odd on the right...
if n mod 2 = 0 then
m_threadoutputs(n).location = new system.drawing.point(margin * 2, y)
else
m_threadoutputs(n).location = new system.drawing.point(midpoint, y)
end if
m_threadoutputs(n).size = new system.drawing.size(controlwidth, controlheight)
m_threadoutputs(n).visible = true

vb won't know it needs to manage the control unless we add it to its controls array:

' finally, add the object to the list of controls on the form...
me.controls.add(m_threadoutputs(n))

our last job is to adjust the y co-ordinate if we just added an odd number control and then close the loop:

' then, work out the next y co-ordinate for the control if we're an
' odd numbered control...
if n mod 2 = 1 then y += 20 + margin

next



end sub


if we run the code now, we'll see something like this:



now we can look at actually creating the threads!

creating "myworkthread"
myworkthread is going to need the following controls:

m_thread - an instance of a system.threading.thread object that lets us control the thread,
m_pause - an instance of a system.threading.manualresetevent object that lets us pause and resume the thread,
m_iscancelled - a boolean flag telling is if the thread has been cancelled,
m_control - a reference to the textbox control we create dynamically on the main form.
create a new class called myworkthread and add these namespaces:

imports system
imports system.threading
imports system.winforms

then, add references to the member variables to the class definition. also, add the keyword mustinherit to the class definition. this means we won't be able to ever instantiate an instance of myworkthread, just classes derived from it. (in fact, our use of the mustinherit keyword means that we can never create an instance of a myworkthread object.)

public mustinherit class myworkthread



' create somewhere to hold the thread details...
private m_thread as thread
private m_pause as new manualresetevent(true)
private m_iscancelled as boolean
private m_control as textbox


to get and set the text box, we need a property called control:

' create a common property for setting our reporting control...
public property control() as textbox
get
return m_control
end get
set
m_control = value
end set
end property

to make life easier for the threads, we create another method that lets us change just the text on the boxes. so that we can see what's going on, we prefix the value we get with the name of the class. that way, we can see at a glance what class set the message.

' create a common property for updating our control...
public property controltext() as string
get
return m_control.text
end get
set
m_control.text = me.tostring & ": " & value
end set
end property

finally, we need a method that will return a reference to the main application form. the parent member of textbox will return a winform object to us, but a winform object is no use to us if we want to get hold of properties and methods that we define on form1. what we need to do is cast the winform object to a form1 object, which we do using ctype:

' create a property that will return the parent of the text box
' control, cast to a "form1" type...
public readonly property mainform() as form1
get
return ctype(control.parent, form1)
end get
end property

creating a thread
creating a thread in vb.net is really easy. all you have to do is instantiate a class and identify a method on that class as the entry point for the thread. we're going to assume that on wordcounter and charcounter, this method will always be called startthreading. add this method to the myworkthread class definition, making sure you include the mustoverride directive. this forces anyone deriving from myworkthread to include his or her own definition of startthreading. (c++ developers: this is a pure virtual function.)

' create a common mustoverride member to handle thread startup...
public mustoverride sub startthreading()

to start the thread, we're going to call the go method. this creates a new threadstart object, then creates a new thread object and then starts the thread:

' create something that will startup the thread...
public sub go()

' create a threadstart to fire the thread...
dim start as threadstart
start = new threadstart(addressof me.startthreading)

' now, initialize and kick off the thread...
m_thread = new thread(start)
m_thread.start()

end sub

the addressof keyword returns a delegate to the startthreading method in the class. (c++ developers: this is a function pointer.) for some reason, you can't dim threadstart and provide a value in one line - it throws a weird error. it must be done on two separate lines.

when the thread is finished, we're going to assume that it calls the finish method. all this does is set the text box to read finished, but we could do something cooler in here if we wanted.

' finish - a method that's called when the thread stops processing...
public sub finish()
controltext = "finished!"
end sub

events
one curious thing about threading is that an "event" is not the same as a vb event, such as the onclick method of a button winform control. this is because threading has its roots in traditional win32 programming, which did not have events. an event in a threading context identifies something that happens to release a lock on an object. so, if your thread is blocking on a lock waiting for it to become free, when that lock does become free an "event" will be thrown and you'll stop blocking and be able to go into the locked code to do your processing.

the system.threading namespace contains an object called manualraiseevent. this is an object that exists to do nothing but provide -a block that can be in one of two states - signalled and non-signalled. if the block is non-signalled, it's "blocked", i.e. you can't go through it. if it's signalled, you can.

(for c++ developers, this is equivalent to the win32 api createevent call.)

we're going to use a manualraiseevent to control our pause/resume functionality. our thread is going to go around in an infinite loop. at the top of the loop it's going to ask the owner form for a copy of the text in the text box. ("copy" is an important word here, and we'll discuss this in a moment.) it will then do its work, report its results and then "pause" itself. whenever the text in the top box changes, all of the threads will be asked to "resume" themselves, and the cycle repeats. we can also ask the thread to cancel, in which case it will drop out of the infinite loop and come to a natural finish.

to pause the thread, we need to "reset" the manualraiseevent object. this will put it into a non-signaled state:

' pause - tell a thread to pause...
public sub pausethread()
m_pause.reset()
end sub

to resume the thread, we need to "set" the object. this will put it into a signaled state:

' resume - tell a thread to resume processing...
public sub resumethread()
m_pause.set()
end sub

if we want to cancel the thread, we have to set the cancelled flag to true, and resume the thread:

' cancel - stop the thread...
public sub cancel()

' flag us as cancelled...
m_iscancelled = true

' resume the thread...
resumethread()

end sub

it's worth noting that this isn't a "stop now or else" style command. this is a "can you finish up what you were doing and finish gracefully" style command. ideally, when writing multithreaded code, this is the approach you want - get everything to finish naturally, rather than forcing it.

we'll include this, as it might be useful to know if we've been cancelled:

' iscancelled - are we cancelled?
public function iscancelled() as boolean
return m_iscancelled
end function

the last major method we need on this object is ispaused. this is a bit of a misnomer, because if the thread is paused, it won't return - effectively it is the blocking function. what we will do, though, is return the opposite of iscancelled out the other side. this will tell us if we should "keep working" or "quit". what happens when it's used is that the thread will come along say "am i paused". if it is paused, this function won't return. the thread will drop into a wait state at this point until a time when it's no longer paused. when it's not paused, it returns whatever iscancelled is set to. so, if the thread has been cancelled, ispaused will return false. if the thread hasn't been cancelled, it will return true.

' ispaused - tells a thread to continue...
public function ispaused() as boolean

' wait on the pause object...
m_pause.waitone()

' now, return the opposite of cancelled, i.e.
' true means "keep going", false means "stop".
return not iscancelled()

end function

the waitone method is a member of manualresetevent. it tells windows to block the thread until the object is signaled. (c++ developers: this is waitforsingleobject.)

finally, we want one final method that waits for the thread itself to finish. the join method on thread will wait until the thread has neatly finished its work:

' waituntilfinished - keeps waiting until the thread is ready to close...
public sub waituntilfinished()
m_thread.join()
end sub

calling the threads
to call the threads, we need to wire in code behind the cmdstartthreads button. before we do this, though, we need to define charcounter and wordcounter, otherwise vs.net will keep throwing errors while we're writing the code.

building "charcounter"
first of all in charcounter, we set the text of our control to started. notice how we've inherited from myworkthread, and how we've provided a definition for the compulsory startthreading member:

imports system
imports system.winforms
imports system.threading

public class charcounter
inherits myworkthread

public overrides sub startthreading()

' tell it we've started....
controltext = "started!"

now we can drop into our infinite loop. we use ispaused to wait for a signal indicating that we need to process the results, or quit the loop:

' go into a loop and wait until we're asked to start processing...
do while true

' are we paused?
if ispaused() = false then
exit do
end if

next, we do the work and update our results. (we'll see the worktext property in a moment.)

' get hold of the text...
dim worktext as string = mainform.worktext
if worktext.length = 1 then
controltext = "1 char"
else
controltext = worktext.length.tostring & " chars"
end if

after we've done our work, we pause ourselves. the loop will flip back to the beginning and start blocking on ispaused again, until the next time we are resumed.

' put the thread back into a wait state...
pausethread()

loop

finally, if we have finished, we call finish:

' tell it we've finished...
finish()

end sub

end class

building "wordcounter"
wordcounter is virtually identical to charcounter:

imports system
imports system.winforms
imports system.threading

public class wordcounter
inherits myworkthread

public overrides sub startthreading()

' tell it we've started....
controltext = "started!"

' go into a loop and wait until we're asked to start processing...
do while true

' are we paused?
if ispaused() = false then
exit do
end if

' get hold of the text...
dim worktext as string = mainform.worktext

' split the text into words...
dim words() as string = worktext.split(" ".tochararray)

' report the number of words...
if words.length = 1 then
controltext = "1 word"
else
controltext = words.length & " words"
end if

' put the thread back into a wait state...
pausethread()

loop

' tell it we've finished...
finish()

end sub

end class

supporting the threads
now we can tweak form1 and get it to actually create our threads. the first thing we need is a property to get and set the text from the text box on the form that contains the text we want to process. this is where our thread synchronization comes in. whenever we hear a textchanged event on this text box, we want to set the value for the worktext property, but only if no one is reading it. (if threads are reading it, we need to wait until they've all finished, then we go in and write it.) likewise, when any of our threads start, they're going to want to get the value for the property, but only if no one is writing it. therefore, we need to create a reader/writer lock that protects this property from any synchronization problems.

first off, create these member variables at the top of form1:

' create somewhere to keep track of all the threads...
const numthreads as integer = 1
dim m_threadoutputs(numthreads) as textbox
dim m_threads(numthreads) as myworkthread

' create somewhere to keep hold of the text...
dim m_worktext as string
dim m_worktextlock as new readerwriterlock()

a system.threading.readerwriterlock creates the lock that we've been talking about. to use it, we build a property that looks like this:

' create a property that returns the text to process... we want to
' handle reader/writer locks properly...
public property worktext() as string
get

' lock the object for reading...
m_worktextlock.acquirereaderlock(-1)

' get the value back, as we're sure no one's writing it...
worktext = m_worktext

' release the lock on the object...
m_worktextlock.releasereaderlock()

end get
set

' lock the object for writing...
m_worktextlock.acquirewriterlock(-1)

' set the value, as we're sure no one's reading it
' and no one else is writing it...
m_worktext = value

' release the lock...
m_worktextlock.releasewriterlock()

end set
end property

the -1 that we specify to acquirereaderlock and acquirewriterlock tells the object that we want to wait "forever" for the lock to become available. this is a fairly typical thing to find in multithreaded code and can cause problems if not done with respect. it's of paramount importance that you properly unlock blocks of code once you've finished using them. for example, if we forget to release a "write" lock, no other locks can ever been opened and everything will grind to a halt. you also have to have the same number of "lock" and "unlock" commands, e.g. if you lock something five times, you have to unlock it five times.

what's smart about this is that it's transparent to the calling thread - i.e. we've taken all the complexity of synchronizing access to the data and isolated the problem and solution from the thing that needs to use it. each of our 16 threads will call form1.worktext to find out what text it's supposed to be processing. if it's not allowed to have access to the m_worktext data because it's in the process of being changed, this call will automatically block until the owner of the "write" lock has finished.

to create the threads, we need a function called startthreads. this will firstly loop through all the threads that we know about, creating either a wordcounter or charcounter thread, depending on the thread number:

sub startthreads()

' create new threads...
dim n as integer
for n = 0 to numthreads - 1

' create a thread...
select case n mod 2
case 0
m_threads(n) = new wordcounter()
case else
m_threads(n) = new charcounter()
end select

once we've created the thread, we tell the object which text box we want it to report its results in and start things running:


' configure the thread and start it...
m_threads(n).control = m_threadoutputs(n)
m_threads(n).go()

next

end sub

of course, we need to wire startthreads into the cmdstartthreads button:

protected sub cmdstartthreads_click(byval sender as object, _
byval e as system.eventargs)
startthreads()
end sub

to make the threads respond to a change, we need to respond to the textchanged event. firstly, we copy the value in the text box to our m_worktext member variable using the worktext property. this ensures that the locking is done properly, i.e. the value cannot be set if any of the other threads are reading it.

public sub txttext_textchanged(byval sender as object, _
byval e as system.eventargs) handles txttext.textchanged

' update our value...
worktext = txttext.text


once we've set the property, we loop through all of our threads and tell them to resume:

' now, resume all of our threads...
dim n as integer
for n = 0 to numthreads - 1
if not m_threads(n) is nothing then m_threads(n).resumethread()
next

end sub

that's it! now if you click startthreads and change the text in the text box, the threads will process the text and return their results.



closing the threads
stopping the threads is the same deal as creating them:

sub stopthreads()

' loop through the threads stopping them as we go...
dim n as integer
for n = 0 to numthreads - 1

' do we have a thread?
if not m_threads(n) is nothing then

' tell the thread to cancel...
m_threads(n).cancel()

' now, wait for the thread to stop...
m_threads(n).waituntilfinished()

' finally, remove the thread...
m_threads(n) = nothing

end if

next

end sub

this time, however, we call cancel to tell the thread to finish working. it will stop blocking on ispaused, quit the loop and get to the end of startthreading. when startthreading returns, the thread is considered to be "dead". waituntilfinished will call join on the m_thread object and will block until the thread dies, i.e. we return from startthreading.

for neatness, we need to call stopthreads when the application itself closes:

public sub threadform_closing(byval sender as object, _
byval e as system.componentmodel.canceleventargs) handles form1.closing
stopthreads()
end sub

conclusion
in this article we saw how threads can be used in .net courtesy of the system.threading namespace. we also saw a practical example of synchronization in use, and how multiple threads can be used to work on the same piece of data. finally, remember that although this article has been focused on visual basic, the same techniques work exactly the same in c#.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表