当前位置:编程学习 > C#/ASP.NET >>

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

答案: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 a

上一个:一步一步安装VB.Net(图片较多,请稍等)
下一个:Visual Basic.NET带来的新方法(二)

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,