CHAPTER 10
THREAD AND PROCESS
1. Multithreaded Processing – Concept
Linux and Windows operating systems are multitasking systems that allow you to run multiple operating systems at the same time. As you know, a program is simply a list of CPU instructions to perform a specific task. Before a program can be executed, the instructions must reside in the computer's random access memory (RAM).
In general, you can think of a program as a list of instructions and a process as an object that holds information about the running program. Every time you run a program, Windows creates a new process to hold the program's state and resource information.
For example, if you have three programs running (processes 1, 2, and 3), Windows will execute some instructions from process 1 for a few microseconds. It will then switch to process 2 for a few more microseconds, and then it will switch to process 3. Because the operating system switches CPU instructions so quickly, it will appear that the programs are running at the same time.
2. Thread Processing
2.1. Create and run multiple threads
A thread corresponds to an executing program, to use threads in a Visual Basic 2005 program, you must first create a thread object for each thread you plan to use. For example, the following code creates 3 thread objects X, Y and Z:
Dim X As System.Threading.Thread Dim Y As System.Threading.Thread Dim Z As System.Threading.Thread
A thread executes a set of instructions in your program. When you create an instance of a thread you must specify the address of the first statement that the thread will execute, which is usually the address of a subroutine or procedure.
The following statements will assign different execution addresses to the thread object. Thread A will start executing the procedure DisplayA similarly to B which is DisplayB and C which is DisplayC:
A = New Threading.Thread(AddressOff DisplayA) B = New Threading.Thread(AddressOff DisplayB) C = New Threading.Thread(AddressOff DisplayC)
AddressOff is a special instruction of Visual Basic language. It allows to access the address area where the function address exists in memory. With the AddressOff function you can perform very powerful tasks equivalent to the concept of pointer in traditional C language.
Each procedure in this case, quite simply, executes a loop that prints out the thread name (like “A”, “B” or “C”) 100 times, then terminates the subroutine and aborts the thread.
Sub DisplayA()
For I As Integer = 0 To 100
Console.Write(“A”)
Next End Sub
To start thread execution, the program code must call the Start method of the thread class as follows:
A.Start()
B.Start()
C.Start()
2.2. Put the thread into sleep state
Depending on the thread's behavior in your program, there may be times when you need to suspend the execution of a thread for a period of time. For example, you create a thread to monitor the resource usage of a server. Within the program, you can use a periodic timer to check available memory, a one-second timer to survey free disk space, and a three-second timer to check remote user connections to the server. Depending on your needs, you may want to wake up the thread and execute the process every minute or maybe every 10 minutes. To suspend a thread for a period of time, you can use the Sleep method provided by the thread class. For example, the following statement will pause (or sleep) for 7000 milliseconds (1 second = 1000 mini-seconds).
Thread.Sleep(7000)
When you put a thread to sleep using the Sleep method, the thread will not execute and will not consume CPU resources.
The following ThreadSleep.vb program starts 3 threads. Then uses the Sleep method to suspend a thread for 0.3 seconds, 0.1 seconds and 0.8 seconds.
2.3. Stop, Restart, Abort thread
In your program, use threads to perform special tasks.
You use Sleep to stop a thread for a known amount of time. However, if you don't know how long it will take, you can call the Suspend method to stop a thread indefinitely.
Mythread.Suspend()
Similar to Sleep, Suspend puts the thread into sleep mode but does not have time to automatically wake up. To wake the thread back up, you call the Resume method as follows:
Mythread.Resume()
If you don't want to use the thread anymore, you can cancel the thread to free up resources by calling Abort() as follows:
Mythread.Abort()
2.4. Get thread information
To know the information about the active thread, the thread class provides you with many methods such as IsAlive to determine whether the thread is still active or not, Priority to determine the priority, threadState to determine the state of the thread.
2.5. Wait for other threads to complete processing tasks
When your program uses threads to process, there will be times when you need to wait for processing, there will be times when you need to wait for another thread to finish before a thread can continue processing. The thread class provides you with the Join method.
Downloading.Join()
2.6. Thread priority control
When a Visual Basic 2005 application uses multiple threads of execution, the system assigns CPU time to each thread. When a thread is running, the system typically allocates 33% of the CPU time to the thread. Remember, in a multitasking operating system like Windows, the operating system shares CPU time with each application in turn.
Depending on the task that a thread is performing in your application, there may be times when one thread is more important than another. In such cases, your program may give the thread a higher priority, causing it to spend more time on the CPU. To increase or decrease the priority of a thread, you assign a priority value to the Priority property of the thread class. The System.Threading.ThreadPriority namespace provides priority constants: Lowest, BelowNormal, Normal, AboveNormal, and Highest. The following example assigns the Downloader thread the highest priority:
Downloader.Priority = ThreadPriority.highest
Chapter 11
Windows Service Programming
1. Introduction to Windows Services
In the Windows environment, a Service is a special program that runs in the background to perform a certain task. For example, a printer queue needs a Service to monitor the processing of printing tasks sent by an application program. Similarly, Internet Information Services (IIS) runs in the background to send Web pages and files to a client's browser. Visual Studio allows programmers to easily create Windows Services. In this chapter, you will learn how to create the subprograms that each Service must provide to communicate with Windows. You will step by step perform the settings and run the Service each time Windows starts. We will study how to build a simple Service in Windows, install and remove the Service. You will learn how to use the ServiceBase class as well as write Service events to the Event Log, requesting the Service to perform tasks periodically. We will also learn how to use Threads in Services, how to notify administrators when problems occur with the system, and finally we will integrate the FileSystemWatcher program from chapter 2 into a Windows Service.
To view the list of Windows services, follow these steps:
1. Start / Settings / Control Panel.
2. In the Control Panel window, select Administrative Tools.
3. In the Administrative Tools window, select the Services icon.
Visual Studio makes it easy to create a Windows Service. Creating a Service is similar to creating a normal program. Visual Studio generates a skeleton for you to add code to control the Service's functionality.
2. Build a simple Windows Service.
In this section, you will create and then install a Windows Service. To help you get started writing a Service, Visual Studio provides a Windows Service project type, which you select in the New Project dialog box instead of a Windows Service project.
A typical Windows Application. The service we create in this chapter will be named DemoService.
Our Service, in this case, will not perform any processing. Instead, the service will log some of its operations in an event file on the root disk, the DemoEvents.log file. The service will log the start and end times of the service.
To create a Windows service using Visual Studio, follow these steps:
1. In Visual Studio, select File / New Project.
2. Visual Studio displays the New Project dialog box.
3. In the New Project dialog box, select the Windows Services icon. Type a name for the Service in the Name box and click OK.
4. Visual Studio will display a window representing the Service.
5. In the Design View screen, right-click on Project.
6. Visual Studio will display a Popup menu. Select Properties from the menu. Visual Studio will display the properties of the service.
In the list of properties, assign the name DemoService to the Service property (not the Name property). Click Code View to see the implementation code of DemoService. As mentioned, every time DemoService starts, the service appends a message string to the log file. To implement the file import operation, you need to import the System.IO namespace as follows:
Imports System.IO
Then put the following statements in the OnStart method that Visual Studio generates for you.
As you can see, the file open statement then uses the WriteLine() method to write the data. To make the file reusable, we do not close the file in the OnStart() method. In the OnStop() method we write a message saying that the Service is finished and the file previously opened in OnStart() will be closed.
Before you can install the service on your Windows system, you must add the installation code to the DemoService project, by doing the following:
1. Select Design View and right-click on the window to display the popup menu.
2. In the Popup menu, select Add Installer. Visual Studio will add two components to the project, Service Process Installer and Service Installer.
When Windows installs a service, it installs the context in which the service's privileges can be used. If you use the Service Process Installer that Visual Studio adds to your project, you must specify a system account (a special account you create for the service) that will be allowed access to the service context. First, you must select the account type as described in the table below:
Account type
Purpose | |
Local Service | Windows Service Orientation runs services in the local context with certain privileges. |
Network Service | Instruct Windows to run the service in a non-privileged context using a local account. |
Local System | Local system, equivalent to an anonymous account logged in to use the system. |
User | Windows is required to ask for username and password directly every time a service is run in a user context. |
Maybe you are interested!
-
Database Programming - Hanoi Industrial Vocational College - 22 -
Database Programming - Hanoi Industrial Vocational College - 1 -
Database - Hanoi Industrial College - 2 -
Practice database programming with VB.net - 39 -
SQL Database Administration - Hanoi University of Business and Technology - 14

Next, specify the username for the account. If you do not specify the account context information, Windows will not be able to install the service. To specify the service's installation information, right-click on the ServiceProcessInstaller entry in the window.
Properties, you specify the account type as shown in Figure 9-5 and select the user type. Next, compile the service. At this stage, your service needs to contain processing statements, here we simply write to the log file in the OnStart() and OnStop() events of the service. Select Build / Build DemoService from the menu to compile.
3. Install and remove Services in Windows
In the above example, after compilation we have a Windows service named DemoService.exe. You must instruct Windows to install the service (run the service program in the background) when your system starts. One of the easiest ways to install the service is to use the InstallUtil program (provided by Visual Studio) which you can run from the command line. To install DemoService.exe, open a Command window and type the following InstallUtil command:
InstallUtil PathDemoService.exe
Where Path is the directory path of the DemoService.exe file. Pay attention to the messages generated by InstallUtil.exe. If the service installation fails, you will receive a message stating the cause of the error. After the InstallUtil command finishes successfully, your service is installed on your Windows system, but it will not be running yet (you will learn how to make it start automatically later). To manually start the service, follow these steps:
1. Select Select Start / Settings / Control Panel. Windows will display the Control Panel window.
2. In Control Panel, double-click the Administrative Tools icon. In the Administrative Tools window, double-click the Services icon.
3. In the Services window, right-click the service you want to start and then select Start.
In addition to using the Windows Services manager above, you can also start the Service directly from Visual Studio using the Server Explore window. You perform the following steps:
1. In Visual Studio, select View / Server Explore, Visual Studio will open the Server Explore window.
2. In Server Explore, click on the server that corresponds to your system and then select the service listed in the Services section.
3. In the list of services, right-click the service you want to start and then select Start from the toolbar menu.
When you no longer require a service, you can use the InstallUtil command again to remove the service. In this case, we use the /U switch to use the Uninstall function as follows:
InstallUtil /U PathDemoService.exe
4. Using the ServiceBase class
When you create a Windows service, your service uses the ServiceBase class located in the System.ServiceProcess namespace.
The ServiceBase class represents the process that Windows creates to execute requests to the service. By overriding the base class method, we redefine the operations the service performs when it starts, pauses, or stops, and then continues the service's operations.
To check the service event can be paused, resumed, or Shutdown. We do the following steps:
- In design mode, press the service key and select the properties menu
- In the list of listed services, we use the drop-down to enable or disable events for the service.
- CanHandlePowerEvent = true
- CanPauseAndContinue = true
- CanShutdown = true





