Introduce VB.NET Threads (English)

zhaozj2021-02-08  452

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

What is a tenread?

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 is not 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 do not 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 THRE ad 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 of the responses from EACH of the servers.Without threading, you have to do this job sequentially, ie 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 does not 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 Program REPRESENTS.

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 (eg 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 beread or Changing That 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 what 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-effect because you're create bottlenecks when you don't need it. 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 - IE WAwant Synchronous Access. What We do is ask for "Reading".

Imagine We since the value. Well, in this case Want Anyone else to write to it, we ask for "write" Writing ".

In Both Cases, IF WAWANT 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, Province A More Meaningful Locking Mechanism That Will Only Create Bottlenecks When Appriate.

Although our example is not very meaningful, you must think hard about synchronisation whenever you're using threading. In Visual C , writing code that did not 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 Wouldten Point Out WHERE you'd Gone Wrong. in vb.net, You're Working At a higher level and so the chances of crashing area 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 ustement in the system.threading namespace. Specification, the object we need to use to create a thread is the system.threading.thread object ..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 does not 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 does not 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 will not be changing constantly (or, if it is, we can actually process the text faster than the user can type), we do not 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 CALED 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 could not 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 Figure 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 nuTreads 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 anyinitization after the initializationcomponent () CALL

'Work out the distance bagween 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 Pixels and Back Again.

After We since 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 OUTHOW WANT TO, SO We next To Base this on the width of the form, and use our margin value to space everyhes 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 THE

'Any Controls, Given You Want 2x Margin on Both Side ...

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.totring

Next We need to work outhther 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 ... 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 Wo't Know It Needs to Manage The Control Unless: '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 The Loose The loop:

'Then, Work Out the next y co-order for the controliffness ing 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 CANCELED, 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 will not 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 manualReset (TRUE)

Private m_iscancelled as boolean

Private M_Control As TextboXTo 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 useing 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, THREATES A New Thread Object and the 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 not Dim ThreadStart and provide a value in one line - it throws a weird error It.. Must Be done on two separate lines.

.

'Finish - a Method That's Called When THREAD Stops Processing ...

Public Sub Finish ()

ControlText = "Finished!"

End subevents

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 ", IE you can't go through it. if it's signalload, 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 The Text In The Top Box Changes, All of 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 Into a non-signal-signal 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 signalted 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 Cancelle ...

m_iscancelled = true

'Resume the Thread ...

ResMethread ()

End Sub

It's worth noting that this is not 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 cancellated:

'ISCANCELED - Are We Cancelle?

Public function iscancelled () as boolean

Return m_iscancelle

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 will not 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 will not 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. 'ISPASED - TELLS A Thread To Continue ...

Public function ispaused () as boolean

'Wait on the Pause Object ...

m_pause.waitone ()

'Now, return the oppositive of cancelled, i.e.

'True Means "Keep Going", False Means "STOP".

Return NOT ISCANCELLED ()

END FUNCTION

The Waitone Method Is A Member of ManualReveTevent. 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. NOTED. NOTED. NOTED. NOTED. NOTED ANHERITED 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 the results, or quit the loop:

'Go Into a loop and wait unsteil we're asked to start processing ...

Do While True

'Are We Paused?

IF ispaused () = false kil

Exit do

END IF

Next, we do the work and update ur 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 Ourslves. The Loop Will Flip Back To The Beginning and Start Blocking ON ISPASED 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 unsteil we're asked to start processing ...

Do While True

'Are We Paused?

IF ispaused () = false kil

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 three

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 our threads start, they're going to want to get the value for the profment, but online, we need to create a Reader / Writer Lock That Protects this property from any synchronization problem.

First Off, Create Thase Member Variables At the top of form1: 'create somewhere to keep track of all the threads ...

Const nuTreads 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 ... WEWANT 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 ready

'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, eg 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 - ie 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_workt EXT DATA BECAUSE'S IN The Process of Being Changed, this call will automaticly block untric the output 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 starthreads ()

'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, ie 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 the 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 kil_threads (n) .resumethread ()

NEXT

End Sub

..

Closing the threads

Stopping the threads is The Same Deal as CREATING THEM:

Sub stopthreads ()

'loop through the threads stopping the 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, IE 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 Alth This Article Has Been Focused on Visual Basic, The Same Techniques Work Exactly The Same In C #.

[Download Relative Material]

转载请注明原文地址:https://www.9cbs.com/read-510.html

New Post(0)