VB. NET multithreading technology and its implementation [reprinted]

Source: Internet
Author: User
Abstract: VISAUL basic does not provide a good support for multithreading in versions earlier than 6.0, while Microsoft's. NET Framework provides a new class library to easily create Multithreaded Applications. This article first outlines the relationships between processes, threads, and application domains, and then introduces how to use Visual Basic. Net multi-threaded programming technology to develop applications with higher efficiency and faster response speed.

Keywords. NET Framework Visual Basic. Net multithreading Synchronization

1. Introduction

1.1 process and thread and application domain

In the operating system, a process is defined as a running instance of an application, which is a dynamic execution of the application. A thread is the path for executing the internal program of a process and an execution unit of the process. Basically, a thread is the simplest unit of code that can be scheduled by the system. It is responsible for executing the program code contained in the address space of the process. See figure 1.

In the. NET Framework, the concept of application domain is proposed. All programs are generated after compilation, and the isolation, loading, and uninstallation of these intermediate codes and the provision of security boundaries are implemented through the application domain. In this case, a process can contain one or more application domains, and an application domain can contain one or more threads. This actually adds a new security boundary between processes and threads. No matter within the same process or between different processes, each application domain is independent of each other, different Application domains can only transmit messages and objects through remote communication.


Figure 1 Relationship between processes, threads, and application domains

1.2 significance of Multithreading

A multi-threaded application can make better use of system resources. Its main advantage is to make full use of the free time slice of the CPU and respond to user requirements with as little time as possible, which greatly improves the overall running efficiency of the process, it also enhances the flexibility of applications. More importantly, because all threads of the same process share the same memory, no special data transmission mechanism is required, and no shared storage area or file is required, this makes it easier to solve problems such as coordinated operations and operations between different tasks, data interaction, and resource allocation.

  2. Support for multithreading in visual basic.net

2.1 Support for multithreading in VB

In the old version of VB6.0 and earlier versions, multithreading is rarely involved. This is because VB is NOT thread-safe. The working principle and programming mechanism of multithreading mode are not fully suitable for VB. In VB6.0 applications, we can use Win32 createthread API to create a multi-threaded application, or create a component in an independent thread by deceiving the com library, however, these technologies are difficult to debug and maintain.

2.2 Support for multithreading in Visual Basic. net

Because Visual Basic. net is based on.. NET Framework, and. the Common Language Runtime (Common Language Runtime) is an important component of the. NET Framework. the threading class directly establishes multi-threaded applications and supports advanced functions such as thread pools. Any.. NET Framework, including Visual Basic. net can use the objects and methods provided by the system class when writing multi-threaded applications, instead of using Win32 APIs, therefore, it can greatly reduce the development difficulties and the probability of errors.

3. multi-thread programming implementation in Visual Basic. net

3.1 thread creation and management

The base class used to create and maintain threads is the system. Threading. Thread class. It can create and control threads, set their priorities, and obtain their statuses. It has methods such as start, stop, resume, abort, suspend, and join (wait for) to manipulate threads. It can also use methods such as sleep, isalive, isbackground, priority, apartmentstate and threadstate.

The most direct way to create a thread is to create a new Thread class instance and use the addressof statement to pass tasks for the thread to run.

Run the following code as a separate thread:

Dim thread1 as new system. Threading. Thread (addressof mytask)

Thread1.start

Similarly, the sleep method of the thread class can block the current thread. The suspend method can be used to suspend the thread. The resume method can be used to restart the suspended thread and the abort method can be used to stop a thread, using the join method, the current thread can wait for other threads to finish running.

3.2 thread canceled

One advantage of Multithreading is that the user interface of the application can always respond, even if other threads are executing tasks. Other threads can be notified to stop by the synchronization event and the fields used as the flag. To cancel one or more running threads, you can call the canceltask () method.

3.3 thread priority

Different threads have different priorities, and the priority determines how much CPU time a thread can get. High-priority threads usually get more CPU time than general-priority threads. If there is more than one high-priority thread in the program, the operating system will allocate CPU time cyclically between these threads. Once a low-priority thread encounters a high-priority thread during execution, it will give the CPU to the high-priority thread. In Visual Basic. net, system. Threading. thread. Priority enumerated the priority levels of threads, including highest, abovenormal, normal, belownormal, and lowest. The initial priority of the newly created thread is normal.

Status of 3.4 threads

A thread must be in a certain state from creation to termination, which is defined by the system. Threading. thread. threadstate attribute. When a thread is just created, it is in the unstarted state, and the START () method of the thread class changes the thread state to the running state, if the corresponding method is not called to suspend, block, destroy, or terminate the thread, the thread will remain in this state. The suspended thread is in the sudedded State until we call the resume () method to re-execute it. At this time, the thread will change to the running state again. Once a thread is destroyed or terminated, the thread is in the stopped state, and the thread in this State no longer exists. The thread also has a background status, which indicates whether the thread runs on the foreground or background. At a specific time, the thread may be in multiple States. See figure 2.


Figure 2 thread state conversion

3.5 Thread Pool

Multi-threaded operations in applications can optimize application performance, but multithreading often requires more code and energy to control threads and implement polling and state conversion between threads. The thread pool can automatically complete these tasks and optimize the computer access performance, so as to take advantage of multithreading more effectively. With the thread pool, you can use the delegate of the process to be run to call the threadpool. queueuserworkitem method. VB. NET will create a thread and run the process. The following code uses the thread pool to start multiple tasks.

Sub domywork ()

Dim mypool as system. Threading. threadpool queues a task

Mypool. queueuserworkitem (new system. Threading. waitcallback (addressof task1 ))

Mypool. queueuserworkitem (new system. Threading. waitcallback (addressof task2 ))

End sub

If you want to start many independent tasks, but you do not need to set the attributes of each thread separately, the thread pool will be very useful. Each thread is started with the default stack size and priority. By default, each system processor can run a maximum of 25 thread pool threads. Other threads that exceed this limit will be queued until the other threads finish running.

The thread pool is not applicable in all cases. When a thread with a specific priority needs to be implemented, it cannot be implemented through the thread pool.

3.6 Thread Synchronization

In multi-threaded applications, we need to consider data synchronization between different threads and prevent deadlocks. A deadlock occurs when two or more threads wait for the other party to release resources at the same time. To prevent deadlocks, we need to implement thread security through synchronization. In Visual Basic. net, three methods are provided to synchronize threads.

(1) code domain synchronization: The monitor class can be used to synchronize all or part of code segments of static/instantiated methods.

(2) manual synchronization: You can use different synchronization classes (such as waithandle, mutex, readerwriterlock, manualresetevent, autoresetevent, and interlocked) to create your own synchronization mechanism. This synchronization method requires you to manually synchronize different domains and methods. This synchronization method can also be used to synchronize between processes and remove deadlocks caused by waiting for shared resources.

(3) Context synchronization: Use synchronizationattribute to create simple and automatic synchronization for the contextboundobject object. This synchronization method is only used for the synchronization of Instantiation methods and domains. All objects in the same context domain share the same lock.

  4. Conclusion

This article discusses the multithreading Development Technology in Visual Basic. net. Multithreading is a good choice for implementing applications that require concurrent execution, especially for blocks that are blocked most of the time, such as accessing network resources during development, operations with high system overhead or quick User Interface response are irreplaceable. However, each thread requires additional memory to be created, and the processor time slice is also required to run and manage threads. Therefore, if too many threads are created, the performance of the application will be reduced. Therefore, when designing multi-threaded applications, we should exercise caution and establish a reasonable system model so that the application can obtain the best performance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.