- •About the Authors
- •Contents at a Glance
- •Contents
- •Introduction
- •Goal of the Book
- •How to Use this Book
- •Introduction to the .NET Framework
- •Common Language Runtime (CLR)
- •Class Library
- •Assembly
- •Versioning
- •Exceptions
- •Threads
- •Delegates
- •Summary
- •Introduction to C#
- •Variables
- •Initializing Variables
- •Variable Modifiers
- •Variable Data Types
- •Types of Variables
- •Variable Scope
- •Types of Data Type Casting
- •Arrays
- •Strings
- •Initializing Strings
- •Working with Strings
- •Statements and Expressions
- •Types of Statements
- •Expressions
- •Summary
- •Classes
- •Declaring Classes
- •Inheritance
- •Constructors
- •Destructors
- •Methods
- •Declaring a Method
- •Calling a Method
- •Passing Parameters to Methods
- •Method Modifiers
- •Overloading a Method
- •Namespaces
- •Declaring Namespaces
- •Aliases
- •Structs
- •Enumerations
- •Interfaces
- •Writing, Compiling, and Executing
- •Writing a C# Program
- •Compiling a C# Program
- •Executing a C# Program
- •Summary
- •Arrays
- •Single-Dimensional Arrays
- •Multidimensional Arrays
- •Methods in Arrays
- •Collections
- •Creating Collections
- •Working with Collections
- •Indexers
- •Boxing and Unboxing
- •Preprocessor Directives
- •Summary
- •Attributes
- •Declaring Attributes
- •Attribute Class
- •Attribute Parameters
- •Default Attributes
- •Properties
- •Declaring Properties
- •Accessors
- •Types of Properties
- •Summary
- •Introduction to Threads
- •Creating Threads
- •Aborting Threads
- •Joining Threads
- •Suspending Threads
- •Making Threads Sleep
- •Thread States
- •Thread Priorities
- •Synchronization
- •Summary
- •Case Study
- •Project Life Cycle
- •Analyzing Requirements
- •High-Level Design
- •Primary and Foreign Keys
- •Referential Integrity
- •Normalization
- •Designing a Database
- •Low-Level Design
- •Construction
- •Integration and Testing
- •User Acceptance Testing
- •Implementation
- •Operations and Maintenance
- •Summary
- •Creating a New Project
- •Console Application
- •Windows Applications
- •Creating a Windows Application for the Customer Maintenance Project
- •Creating an Interface for Form1
- •Creating an Interface for WorkerForm
- •Creating an Interface for CustomerForm
- •Creating an Interface for ReportsForm
- •Creating an Interface for JobDetailsForm
- •Summary
- •Performing Validations
- •Identifying the Validation Mechanism
- •Using the ErrorProvider Control
- •Handling Exceptions
- •Using the try and catch Statements
- •Using the Debug and Trace Classes
- •Using the Debugging Features of Visual Studio .NET
- •Using the Task List
- •Summary
- •Creating Form1
- •Connecting WorkerForm to the Workers Table
- •Connecting CustomerForm to the tblCustomer Table
- •Connecting the JobDetails Form
- •to the tblJobDetails Table
- •Summary
- •Introduction to the Crystal Reports Designer Tool
- •Creating the Reports Form
- •Creating Crystal Reports
- •Creating the Windows Forms Viewer Control
- •Creating the Monthly Worker Report
- •Summary
- •Introduction to Deploying a Windows Application
- •Deployment Projects Available in Visual Studio .NET
- •Deployment Project Editors
- •Summary
- •Case Study
- •Project Life Cycle
- •Analyzing Requirements
- •High-Level Design
- •Low-Level Design
- •Summary
- •Populating the TreeView Control
- •Displaying Employee Codes in the TreeView Control
- •Event Handling
- •Displaying Employee Details in the ListView Control
- •Summary
- •Case Study
- •Project Life Cycle
- •Analyzing Requirements
- •High-Level Design
- •Low-Level Design
- •Summary
- •Adding the Programming Logic to the Application
- •Adding Code to the Form Load() Method
- •Adding Code to the OK Button
- •Adding Code to the Exit Button
- •Summary
- •The Created Event
- •Adding Code to the Created Event
- •Overview of XML
- •The XmlReader Class
- •The XmlWriter Class
- •Displaying Data in an XML Document
- •Displaying an Error Message in the Event Log
- •Displaying Event Entries from Event Viewer
- •Displaying Data from the Summary.xml Document in a Message Box
- •Summary
- •Airline Profile
- •Role of a Business Manager
- •Role of a Network Administrator
- •Role of a Line-of-Business Executive
- •Project Requirements
- •Creation and Deletion of User Accounts
- •Addition of Flight Details
- •Reservations
- •Cancellations
- •Query of Status
- •Confirmation of Tickets
- •Creation of Reports
- •Launch of Frequent Flier Programs
- •Summarizing the Tasks
- •Project Design
- •Database Design
- •Web Forms Design
- •Enabling Security with the Directory Structure
- •Summary
- •Getting Started with ASP.NET
- •Prerequisites for ASP.NET Applications
- •New Features in ASP.NET
- •Types of ASP.NET Applications
- •Exploring ASP.NET Web Applications
- •Introducing Web Forms
- •Web Form Server Controls
- •Configuring ASP.NET Applications
- •Configuring Security for ASP.NET Applications
- •Deploying ASP.NET Applications
- •Creating a Sample ASP.NET Application
- •Creating a New Project
- •Adding Controls to the Project
- •Coding the Application
- •Summary
- •Creating the Database Schema
- •Creating Database Tables
- •Managing Primary Keys and Relationships
- •Viewing the Database Schema
- •Designing Application Forms
- •Standardizing the Interface of the Application
- •Common Forms in the Application
- •Forms for Network Administrators
- •Forms for Business Managers
- •Forms for Line-of-Business Executives
- •Summary
- •The Default.aspx Form
- •The Logoff.aspx Form
- •The ManageUsers.aspx Form
- •The ManageDatabases.aspx Form
- •The ChangePassword.aspx Form
- •Restricting Access to Web Forms
- •The AddFl.aspx Form
- •The RequestID.aspx Form
- •The Reports.aspx Form
- •The FreqFl.aspx Form
- •Coding the Forms for LOB Executives
- •The CreateRes.aspx Form
- •The CancelRes.aspx Form
- •The QueryStat.aspx Form
- •The ConfirmRes.aspx Form
- •Summary
- •Designing the Form
- •The View New Flights Option
- •The View Ticket Status Option
- •The View Flight Status Option
- •The Confirm Reservation Option
- •Testing the Application
- •Summary
- •Locating Errors in Programs
- •Watch Window
- •Locals Window
- •Call Stack Window
- •Autos Window
- •Command Window
- •Testing the Application
- •Summary
- •Managing the Databases
- •Backing Up the SkyShark Airlines Databases
- •Exporting Data from Databases
- •Examining Database Logs
- •Scheduling Database Maintenance Tasks
- •Managing Internet Information Server
- •Configuring IIS Error Pages
- •Managing Web Server Log Files
- •Summary
- •Authentication Mechanisms
- •Securing a Web Site with IIS and ASP.NET
- •Configuring IIS Authentication
- •Configuring Authentication in ASP.NET
- •Securing SQL Server
- •Summary
- •Deployment Scenarios
- •Deployment Editors
- •Creating a Deployment Project
- •Adding the Output of SkySharkDeploy to the Deployment Project
- •Deploying the Project to a Web Server on Another Computer
- •Summary
- •Organization Profile
- •Project Requirements
- •Querying for Information about All Books
- •Querying for Information about Books Based on Criteria
- •Ordering a Book on the Web Site
- •Project Design
- •Database Design
- •Database Schema
- •Web Forms Design
- •Flowcharts for the Web Forms Modules
- •Summary
- •Introduction to ASP.NET Web Services
- •Web Service Architecture
- •Working of a Web Service
- •Technologies Used in Web Services
- •XML in a Web Service
- •WSDL in a Web Service
- •SOAP in a Web Service
- •UDDI in a Web Service
- •Web Services in the .NET Framework
- •The Default Code Generated for a Web Service
- •Testing the SampleWebService Web Service
- •Summary
- •Creating the SearchAll() Web Method
- •Creating the SrchISBN() Web Method
- •Creating the AcceptDetails() Web Method
- •Creating the GenerateOrder() Web Method
- •Testing the Web Service
- •Securing a Web Service
- •Summary
- •Creating the Web Forms for the Bookers Paradise Web Site
- •Adding Code to the Web Forms
- •Summary
- •Case Study
- •Project Life Cycle
- •Analyzing Requirements
- •High-Level Design
- •Low-Level Design
- •Summary
- •Overview of Mobile Applications
- •The Microsoft Mobile Internet Toolkit
- •Overview of WAP
- •The WAP Architecture
- •Overview of WML
- •The Mobile Web Form
- •The Design of the MobileTimeRetriever Application
- •Creating the Interface for the Mobile Web Forms
- •Adding Code to the MobileTimeRetriever Application
- •Summary
- •Creating the Forms Required for the MobileCallStatus Application
- •Creating the frmLogon Form
- •Creating the frmSelectOption Form
- •Creating the frmPending Form
- •Creating the frmUnattended Form
- •Adding Code to the Submit Button in the frmLogon Form
- •Adding Code to the Query Button in the frmSelectOption Form
- •Adding Code to the Mark checked as complete Button in the frmPending Form
- •Adding Code to the Back Button in the frmPending Form
- •Adding Code to the Accept checked call(s) Button in the frmUnattended Form
- •Adding Code to the Back Button in the frmUnattended Form
- •Summary
- •What Is COM?
- •Windows DNA
- •Microsoft Transaction Server (MTS)
- •.NET Interoperability
- •COM Interoperability
- •Messaging
- •Benefits of Message Queues
- •Limitations
- •Key Messaging Terms
- •Summary
- •Pointers
- •Declaring Pointers
- •Types of Code
- •Implementing Pointers
- •Using Pointers with Managed Code
- •Working with Pointers
- •Compiling Unsafe Code
- •Summary
- •Introduction to the Languages of Visual Studio .NET
- •Visual C# .NET
- •Visual Basic .NET
- •Visual C++ .NET
- •Overview of Visual Basic .NET
- •Abstraction
- •Encapsulation
- •Inheritance
- •Polymorphism
- •Components of Visual Basic .NET
- •Variables
- •Constants
- •Operators
- •Arrays
- •Collections
- •Procedures
- •Arguments
- •Functions
- •Adding Code to the Submit Button
- •Adding Code to the Exit Button
- •Summary
- •Introduction to Visual Studio .NET IDE
- •Menu Bar
- •Toolbars
- •Visual Studio .NET IDE Windows
- •Toolbox
- •The Task List Window
- •Managing Windows
- •Customizing Visual Studio .NET IDE
- •The Options Dialog Box
- •The Customize Dialog Box
- •Summary
- •Index
94 |
Part II |
HANDLING DATA |
|
|
|
In this chapter, you will be introduced to threads. In addition, you will learn to create and work with threads. This chapter introduces you to the Thread class, which is a .NET base class.This class helps you to create and manipulate threads in applications. This chapter also discusses the states and priorities of threads. Finally, the chapter introduces you to the synchronization of variables across
threads.
Introduction to Threads
Threads are a well-known concept to C and C++ programmers. A thread is a basic unit of the execution of a program. In other words, a thread is the smallest unit to which the operating system allocates processor time. A thread decides the sequence of execution of a program and is very useful for executing complex applications or even multiple applications simultaneously. In addition, you can have a single application containing multiple threads. When the C# compiler executes a multithreaded application, several threads are executed simultaneously. This makes the execution of a complex application less time-consuming.
In a multithreaded application, you can execute multiple activities simultaneously. For example, consider a situation in which you execute a print command for printing 100 pages. Printing 100 pages takes a substantial amount of time. Therefore, you can have two threads working simultaneously on the system. One thread can be used for printing and the other thread can be used to perform any other activity, such as working in a Word document or a spreadsheet.
All the applications that you create involve one or more threads. However, there are some situations in which threads can be used very effectively. Following are examples of some of these situations.
As discussed earlier, you use threads to perform operations that can be time-consuming. In such cases, you can create two threads, a worker thread and a user thread. The worker thread performs time-consuming operations, and the user thread manages user interactions. For example, you can create a worker thread to print 100 pages while the user thread enables you to work in a Word document.
THREADS |
Chapter 6 |
|
95 |
|
|||
|
|
|
|
You can also use threads to transfer data over the network. For example, you need to transfer volumes of data from one branch office to another. In this case, you can create a thread to connect to the server in the other branch.
You also use threads when you need to execute an application that performs more than one operation. For example, when a data entry operator enters data into a database, this data should be updated automatically in the master database. In this case, you can have a worker thread and a user thread. The user thread accepts the input from the user while the worker thread updates the records in the master database.
You have seen that using threads in your application allows you to perform multiple activities simultaneously. However, extensive use of threads in a single application may even deteriorate the performance of your application. To understand this, let us look at the process of execution of threads. Executing threads requires the use of several operating system resources.These resources execute a thread for a very short period of time, known as the time slice of the thread. After executing the thread for this time slice, the Windows operating system chooses another thread to execute.This process of executing multiple threads for a given time slice is called preemptive multitasking. If you have multiple threads in a single application, the operating system spends time switching between various threads after a time slice, which may in turn reduce the performance of the application.
By now, you know that your application can have as many threads as required.The next section looks at creating threads for your application.
Creating Threads
A thread that you create is an instance of the Thread class. The Thread class is a class in the .NET Framework class library and is located in the System.Threading namespace. Therefore, to create an instance of the Thread class, you first need to import the System.Threading namespace. You can then create the object of the Thread class that represents a thread. You can continue to add threads to your application by simply creating multiple instances of the object of the Thread class.
To create a thread, you need to declare an instance of the Thread class and provide it with the details of the method with which the execution of the thread starts. To do so, you can use the public void delegate named ThreadStart() of the System.Threading namespace. You have learned about delegates in Chapter 1, “Overview of the .NET Framework,” in the section “Delegates.”
96 |
Part II |
HANDLING DATA |
|
|
|
Consider the following example.
using System;
using System.Threading; class Class1
{
public void Method1()
{
Console.WriteLine(“Method1 is the starting point of execution of the thread”);
}
public static void Main()
{
Class1 newClass = new Class1();
Thread Thread1 = new Thread(new ThreadStart(newClass.Method1));
}
}
Here, an instance of the Thread class, Thread1, is created. The ThreadStart() delegate specifies the name of the method, Method1, with which the execution of Thread1 starts. Method1 is a public void function defined in Class1. However, creating an instance of the Thread class does not make the thread functional. To start the thread, you need to call the Start() method. The following code shows the syntax for calling the Start() method.
Thread1.Start();
TIP
Because the threads that you define can be used across applications, it is advisable that you give a relevant name to your thread.This enables other programmers to reuse the functionality provided by your thread. To give a relevant name to your thread, you can change the value of the Name property of the thread.
The following code defines a worker thread for updating the records in the master database. It will give the thread a meaningful name, such as
Thread.
THREADS |
Chapter 6 |
97 |
|
|
|
Thread Thread1 = new Thread(new ThreadStart(newClass.Method1));
Thread1.Name = “Update Records Thread”;
The previous code snippet creates an instance of the Thread class with the name Thread1 and then assigns a name Update Records Thread to the thread.
In addition to the Name property that is used to give a meaningful name to a thread, you can use properties to know the status of the executing threads.These properties are defined in the Thread class of the System.Threading namespace.
IsAlive property. The IsAlive property is used to specify that the execution of a thread is complete or the thread is still working. The IsAlive property returns a Boolean value of true for the thread that is working and false for the thread that is not executing.
ThreadState property. The ThreadState property indicates the execution status of a thread. In other words, it returns a value specifying whether the execution of the thread has started or not. You will learn about the states of a thread later in this chapter.
Aborting Threads
You have learned how to create and execute a thread. However, sometimes you may need to stop a running thread. Consider the same old example in which you executed a print command for 100 pages. In this case, a thread is executed to print the required pages. If you need to print some other urgent page, you need to stop the previous print command or, in other words, abort the thread that is printing 100 pages. This section discusses aborting a running thread.
C# provides you with a base class, the Thread class, that you can use to perform several operations with threads. The Thread class contains several predefined methods that enable you to work with threads. To abort a thread, you use the Abort() method of the Thread class. The Abort() method has the following syntax:
Thread1.Abort();
Here, Thread1 is the instance of the Thread class. The Abort() method does not take any parameters. When you call the Abort() method, the C# compiler might not kill the thread instantaneously. To understand why the C# compiler takes time to kill the thread, you first need to understand how the Abort() method is executed.