0% found this document useful (0 votes)
50 views19 pages

Understanding VB.Net Procedures and Functions

The document outlines the concept of procedures in programming, specifically in VB.Net, detailing two types: Sub procedures and Function procedures. It explains how to define and use these procedures, including parameter passing methods, recursion, and built-in functions for date and time operations. Additionally, it covers dialog boxes for user interaction and file I/O operations using the System.IO namespace.

Uploaded by

Kiruthika Mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views19 pages

Understanding VB.Net Procedures and Functions

The document outlines the concept of procedures in programming, specifically in VB.Net, detailing two types: Sub procedures and Function procedures. It explains how to define and use these procedures, including parameter passing methods, recursion, and built-in functions for date and time operations. Additionally, it covers dialog boxes for user interaction and file I/O operations using the System.IO namespace.

Uploaded by

Kiruthika Mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT – 2

PROCEDURES
A procedure is a group of statements that together perform a task when called. After the procedure is
executed, the control returns to the statement calling the procedures.
Types of procedures
They are 2 types of procedures. They are
1. Sub procedure
2. Function procedure
Sub procedure:
It’s performing specific tasks, such as generating an order ID or connecting to a database. Sub
procedures are procedures that do not return any value.
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub procedure.
Syntax :
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
 Modifiers − specify the access level of the procedure; possible values are - Public, Private, Protected,
Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
 SubName − indicates the name of the Sub
 ParameterList − specifies the list of the parameters
Example
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
[Link]("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
[Link]()
End Sub
End Module
Passing Parameters by Value
In this mechanism, when a method is called, a new storage location is created for each value
parameter. The values of the actual parameters are copied into them. So, the changes made to the parameter
inside the method have no effect on the argument. In [Link], to declare the reference parameters using
the ByVal keyword
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass parameters by
reference, unlike value parameters, a new storage location is not created for these parameters. The reference
parameters represent the same memory location as the actual parameters that are supplied to the method. In
[Link], to declare the reference parameters using the ByRef keyword.
The sub main procedure
Its executed first when a visual basic program is run is the main procedures.
1
Syntax:
Sub Main()
-----
End Sub
Functions procedures:
Its perform procedures perform specific tasks and return a value to the calling statement
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function.
syntax
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
 Modifiers − specify the access level of the function; possible values are: Public, Private, Protected,
Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
 FunctionName − indicates the name of the function
 ParameterList − specifies the list of the parameters
 ReturnType − specifies the data type of the variable the function returns

Example program
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function

Function Returning a Value


In a function, can return a value to the calling code in two ways −
 By using the return statement
 By assigning the value to the function name
Recursive Function
A function can call itself. This is known as recursion.
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
2
'calling the factorial method
[Link]("Factorial of 6 is : {0}", factorial(6))
[Link]("Factorial of 7 is : {0}", factorial(7))
[Link]("Factorial of 8 is : {0}", factorial(8))
[Link]()
End Sub
End Module
Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of arguments
passed as a parameter.
Passing Arrays as Function Arguments
To can pass an array as a function argument in [Link].
Built in functions
The Date data type contains date values, time values, or date and time values. The default value of
Date is [Link] (midnight) on January 1, 0001. The equivalent .NET data type is [Link].
The DateTime structure represents an instant in time, typically expressed as a date and time of day
'Declaration
<SerializableAttribute> _
Public Structure DateTime _
Implements IComparable, IFormattable, IConvertible, ISerializable,
IComparable(Of DateTime), IEquatable(Of DateTime)
They can also get the current date and time from the DateAndTime class.
The DateAndTime module contains the procedures and properties used in date and time operations.
'Declaration
<StandardModuleAttribute> _
Public NotInheritable Class DateAndTime

Gets a DateTime object that is set to the current date and time on this computer, expressed as the
Coordinated Universal Time (UTC).

The following table lists some of the commonly used methods of the DateTime structure −
[Link] Method Name & Description

Public Function Add (value As TimeSpan) As DateTime


1 Returns a new DateTime that adds the value of the specified TimeSpan to the value of this
instance.

Public Function AddDays ( value As Double) As DateTime


2
Returns a new DateTime that adds the specified number of days to the value of this instance.

Public Function AddHours (value As Double) As DateTime


3
Returns a new DateTime that adds the specified number of hours to the value of this instance.

Public Function AddMinutes (value As Double) As DateTime


4 Returns a new DateTime that adds the specified number of minutes to the value of this
instance.

3
Public Function AddMonths (months As Integer) As DateTime
5
Returns a new DateTime that adds the specified number of months to the value of this instance.

Public Function AddSeconds (value As Double) As DateTime


6 Returns a new DateTime that adds the specified number of seconds to the value of this
instance.

Public Function AddYears (value As Integer ) As DateTime


7
Returns a new DateTime that adds the specified number of years to the value of this instance.

Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer


8 Compares two instances of DateTime and returns an integer that indicates whether the first
instance is earlier than, the same as, or later than the second instance.

Public Function CompareTo (value As DateTime) As Integer


Compares the value of this instance to a specified DateTime value and returns an integer that
9
indicates whether this instance is earlier than, the same as, or later than the specified DateTime
value.

Public Function Equals (value As DateTime) As Boolean


10 Returns a value indicating whether the value of this instance is equal to the value of the
specified DateTime instance.

Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean


11
Returns a value indicating whether two DateTime instances have the same date and time value.

Public Overrides Function ToString As String


12
Converts the value of the current DateTime object to its equivalent string

To Getting the Current Date and Time


The following programs demonstrate how to get the current date and time in [Link] −
Current Time −
Module dateNtime
Sub Main()
[Link]("Current Time: ")
[Link]([Link])
[Link]()
End Sub
End Module
Output: Current Time: 11 :05 :32 AM
Current Date −
Module dateNtime
Sub Main()
[Link]("Current Date: ")
Dim dt As Date = Today
[Link]("Today is: {0}", dt)
[Link]()
End Sub

4
End Module
Output: Today is: 12/11/2012 [Link] AM
Create a DateTime object in one of the following ways −
 By calling a DateTime constructor from any of the overloaded DateTime constructors.
 By assigning the DateTime object a date and time value returned by a property or method.
 By parsing the string representation of a date and time value.
 By calling the DateTime structure's implicit default constructor.
Formatting Date
A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for
example #12/16/2012#. Otherwise, your code may change depending on the locale in which your application
is running.
Predefined Date/Time Formats
The following table identifies the predefined date and time format names. These may be used by name
as the style argument for the Format function –

Format Description

Displays a date and/or time. For example, 1/12/2012 [Link]


General Date, or G
AM.

Displays a date according to your current culture's long date


Long Date,Medium Date, or D
format. For example, Sunday, December 16, 2012.

Displays a date using your current culture's short date format. For
Short Date, or d
example, 12/12/2012.

Displays a time using your current culture's long time format;


Long Time,Medium Time, orT typically includes hours, minutes, seconds. For example,
[Link] AM.

Displays a time using your current culture's short time format.


Short Time or t
For example, 11:07 AM.

Displays the long date and short time according to your current
f culture's format. For example, Sunday, December 16, 2012 12:15
AM.

Displays the long date and long time according to your current
F culture's format. For example, Sunday, December 16, 2012
[Link] AM.

Displays the short date and short time according to your current
g
culture's format. For example, 12/16/2012 12:15 AM.

Displays the month and the day of a date. For example,


M, m
December 16.

R, r Formats the date according to the RFC1123Pattern property.

s Formats the date and time as a sortable index. For example, 2012-
5
12-16T[Link].

Formats the date and time as a GMT sortable index. For example,
u
2012-12-16 [Link]Z.

Formats the date and time with the long date and long time as
U
GMT. For example, Sunday, December 16, 2012 [Link] PM.

Formats the date as the year and month. For example, December,
Y, y
2012.

Properties and Methods of the DateAndTime Class


The following table lists some of the commonly used properties of the DateAndTime Class −
Sr.N
Property & Description
o

Date
1
Returns or sets a String value representing the current date according to your system.

Now
2
Returns a Date value containing the current date and time according to your system.

TimeOfDay
3
Returns or sets a Date value containing the current time of day according to your system.

Timer
4
Returns a Double value representing the number of seconds elapsed since midnight.

TimeString
5
Returns or sets a String value representing the current time of day according to your system.

Today
6
Gets the current date.

Dialog Box
A dialog box in [Link] is a graphical user interface component that prompts the user for input,
displays messages, or provides options for the user to make choices. It is commonly used to interact with the
user during program execution.
MessageBox:
The MessageBox class in [Link] allows you to display messages or prompts to the user.
[Link]("Hello, World!")

InputBox:
The InputBox function displays a dialog box that prompts the user for input.
Dim name As String = InputBox("Please enter your name:")

OpenFileDialog:
6
The OpenFileDialog control allows the user to browse and select files from the system.
Dim openFileDialog As New OpenFileDialog()
If [Link]() = [Link] Then
Dim selectedFile As String = [Link]
' Process the selected file
End If

SaveFileDialog:
The SaveFileDialog control allows the user to specify a file name and location to save a file.
Dim saveFileDialog As New SaveFileDialog()
If [Link]() = [Link] Then
Dim savePath As String = [Link]
' Save the file to the specified location
End If

ColorDialog:
The ColorDialog control allows the user to select a color.
Dim colorDialog As New ColorDialog()
If [Link]() = [Link] Then
Dim selectedColor As Color = [Link]
' Use the selected color
End If

FontDialog:
The FontDialog control allows the user to select a font.
Dim fontDialog As New FontDialog()
If [Link]() = [Link] Then
Dim selectedFont As Font = [Link]
' Use the selected font
End If

FolderBrowserDialog:
The FolderBrowserDialog control allows the user to browse and select a folder.
Dim folderBrowserDialog As New FolderBrowserDialog()
If [Link]() = [Link] Then
Dim selectedFolder As String = [Link]
' Process the selected folder
End If
The common dialog boxes

Dialog boxes provide a convenient way to interact with users, gather input, and display information.
By using these dialog boxes, to enhance the user experience and make your application more interactive and
user-friendly.
PrintDialog:
The PrintDialog control allows the user to select a printer and configure print settings.
Dim printDialog As New PrintDialog()
If [Link]() = [Link] Then
' Perform printing operation using the selected printer and settings
End If

7
PageSetupDialog:
The PageSetupDialog control allows the user to configure page setup settings for printing.
Dim pageSetupDialog As New PageSetupDialog()
If [Link]() = [Link] Then
' Retrieve and use the selected page setup settings
End If

MessageBox with custom buttons and icons:


To customize the MessageBox by specifying different buttons and icons.
Dim result As DialogResult = [Link]("Do you want to save changes?", "Confirmation",
[Link], [Link])
If result = [Link] Then
' Save changes
ElseIf result = [Link] Then
' Discard changes
ElseIf result = [Link] Then
' Cancel operation
End If

Custom Dialog Form:


To create your own custom dialog form by designing a form and displaying it using the ShowDialog
method.
Dim customDialog As New CustomDialogForm()
If [Link]() = [Link] Then
' Retrieve data or perform actions based on user input in the custom dialog form
End

File I/O and system objects


A file is a collection of data stored in a disk with a specific name and a directory path. When a file is
opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing
through the communication path. There are two main streams: the input stream and the output stream.
The input stream is used for reading data from file (read operation) and the output stream is used for
writing into the file (write operation).
[Link] I/O Classes
The [Link] namespace has various classes that are used for performing various operations with files, like
creating and deleting files, reading from or writing to a file, closing a file, etc. The following table shows
some commonly used non-abstract classes in the [Link] namespace.
I/O Class Description

BinaryReader Reads primitive data from a binary stream.

BinaryWriter Writes primitive data in binary format.

BufferedStream A temporary storage for a stream of bytes.

Directory Helps in manipulating a directory structure.

DirectoryInfo Used for performing operations on directories.

DriveInfo Provides information for the drives.


8
File Helps in manipulating files.

FileInfo Used for performing operations on files.

FileStream Used to read from and write to any location in a file.

MemoryStream Used for random access of streamed data stored in memory.

Path Performs operations on path information.

StreamReader Used for reading characters from a byte stream.

StreamWriter Is used for writing characters to a stream.

StringReader Is used for reading from a string buffer.

StringWriter Is used for writing into a string buffer.

The FileStream Class


The FileStream class in the [Link] namespace helps in reading from, writing to and closing files.
This class derives from the abstract class Stream. To create a FileStream object to create a new file or open
an existing file.
The syntax for creating a FileStream object is as follows.
Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess
Enumerator>, <FileShare Enumerator>)
For example, for creating a FileStream object F for reading a file named [Link] −
Dim f1 As FileStream = New FileStream("[Link]", [Link], [Link])
Parameter Description

The FileMode enumerator defines various methods for opening files. The members
of the FileMode enumerator are −
 Append − It opens an existing file and puts cursor at the end of file, or
creates the file, if the file does not exist.
 Create − It creates a new file.
FileMode  CreateNew − It specifies to the operating system that it should create a new
file.
 Open − It opens an existing file.
 OpenOrCreate − It specifies to the operating system that it should open a
file if it exists, otherwise it should create a new file.
 Truncate − It opens an existing file and truncates its size to zero bytes.

FileAccess FileAccess enumerators have members: Read, ReadWrite and Write.

FileShare FileShare enumerators have the following members −


 Inheritable − It allows a file handle to pass inheritance to the child
processes
 None − It declines sharing of the current file
 Read − It allows opening the file for reading
 ReadWrite − It allows opening the file for reading and writing

9
 Write − It allows opening the file for writing
Advanced File Operations in [Link]
The immense powers of [Link] classes, you need to know the commonly used properties and
methods of these classes.

[Link]. Topic and Description

Reading from and Writing into Text files


1 It involves reading from and writing into text files.
The StreamReader and StreamWriter classes help to accomplish it.

Reading from and Writing into Binary files


2 It involves reading from and writing into binary files.
The BinaryReader and BinaryWriter classes help to accomplish this.

Manipulating the Windows file system


3
It gives a [Link] programmer the ability to browse and locate Windows files and directories.

Error handling
There are several types of errors or exceptions that can occur
Exception Handling
An exception is an unwanted error that occurs during the execution of a program and can be a system
exception or application exception. Exceptions are nothing but some abnormal and typically an event or
condition that arises during the execution, which may interrupt the normal flow of the program.
An exception can occur due to different reasons, including the following:
o A user has entered incorrect data or performs a division operator, such as an attempt to divide by zero.
o A connection has been lost in the middle of communication, or system memory has run out.
o A user has entered incorrect data or performs a division operator, such as an attempt to divide by zero.
o A connection has been lost in the middle of communication, or system memory has run out.
Exception Handling
When an error occurred during the execution of a program, the exception provides a way to transfer
control from one part of the program to another using exception handling to handle the
error. [Link] exception has four built-in keywords such as Try, Catch, Finally, and Throw to handle and
move controls from one part of the program to another.

Keywor Description
d

Try A try block is used to monitor a particular exception that may throw an exception within
the application. And to handle these exceptions, it always follows one or more catch
blocks.

Catch It is a block of code that catches an exception with an exception handler at the place in a
program where the problem arises.

Finally It is used to execute a set of statements in a program, whether an exception has occurred.

Throw As the name suggests, a throw handler is used to throw an exception after the occurrence

10
of a problem.
Syntax for Try/Catch
Assuming a block will raise an exception, a method catches an exception using a combination of the
Try and Catch keywords. A Try/Catch block is placed around the code that might generate an exception. Code
within a Try/Catch block is referred to as protected code, and the syntax for using Try/Catch looks like the
following
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try

Exception Classes
In [Link], there are various types of exceptions represented by classes. And these exception classes
originate from their parent's class '[Link]'.

The following are the two exception classes used primarily in [Link].
1. [Link]
2. [Link]
[Link]:
It is a base class that includes all predefined exception classes, and some system-generated exception
classes that have been generated during a run time such as DivideByZeroException,
IndexOutOfRangeException, StackOverflowExpression, and so on.
[Link]:
It is an exception class that throws an exception defined within the application by the programmer or
developer. Furthermore, we can say that it is a user-defined exception that inherits
from [Link] class.
Syntax of exception handler block
Try
' code or statement to be executed
[ Exit Try block]
' catch statement followed by Try block
Catch [ Exception name] As [ Exception Type]
[Catch1 Statements] Catch [Exception name] As [Exception Type]
[ Exit Try ]
[ Finally
[ Finally Statements ] ]
End Try
Creating User-Defined Exceptions
To define your own exception. User-defined exception classes are derived from
the ApplicationException class.
Throwing Objects
In [Link] exception handling, we can throw an object exception directly or indirectly derived from
the [Link] class. To throw an object using the throw statement in a catch block, such as:

11
Throw [ expression ]
Namespace
As programming languages have evolved, the frameworks around them have greatly increased in size.
The .NET framework provides a huge number of base classes, data types, algorithms, etc.

Declaring a Namespace
Namespaces are declared using the namespace keyword. The basic syntax for creating a namespace is
very simple, requiring only a name for the new grouping and a code block surrounded by braces:

Syntax:

namespace namespace-name {}
namespace FirstNamespace
{
class Test
{
public void ShowMessage()
{
[Link]("This is the first namespace!");
}
}
}
This code creates a new namespace named "FirstNamespace" and defines a "Test" class containing a
single method that outputs a string to the console
namespace SecondNamespace
{
class Test
{
public void ShowMessage()
{
[Link]("This is the second namespace!");
}
}
}

Additive Namespace Declarations


Namespace declarations are additive. This means that the same namespace definition can be included
in your code in multiple locations. Where two or more matching declarations are made, the contents of the
two namespaces are combined into one.

Referencing a Class in another Namespace

Fully Qualified Names


Namespaces prevent conflicts between the names of classes by isolating the contents of each
namespace.
The Using Directive
To prefix every use of every class, structure, enumeration, etc. with the name of the namespace that
contained it, your code would become unwieldy. To avoid this the using directive can be used.

using FirstNamespace;
12
Nested Namespaces
How classes and other items can be declared within a namespace to provide grouping of code items
and isolation of names to prevent conflicts.
namespace Parent
{
namespace Child
{
namespace Grandchild
{
class Test
{
public void ShowMessage()
{
[Link]("This is a nested namespace!");
}}
}
}
}
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class body, ended
by the End Class statement. Following is the general form of a class definition.
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
 attributelist is a list of attributes that apply to the class. Optional.
 accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend,
Protected Friend and Private. Optional.
 Shadows indicate that the variable re-declares and hides an identically named element, or set of
overloaded elements, in a base class. Optional.
 MustInherit specifies that the class can be used only as a base class and that you cannot create an
object directly from it, i.e., an abstract class. Optional.
 NotInheritable specifies that the class cannot be used as a base class.
 Partial indicates a partial definition of the class.
 Inherits specifies the base class it is inheriting from.
 Implements specifies the interfaces the class is inheriting from.
The Syntax for creating an object
Dim Obj_Name As Class_Name = New Class_Name() ' Declaration of object
Obj_Name.Method_Name() ' Access a method using the object
Member Function
The member function of a class is used to define the structure of member inside the definition of the
class. It can be accessed by all defined objects of the class and operated on the data member. Furthermore,
member variables are the attributes of an object to be implemented to a member function. And we can access
member variables using the public member function.
Constructor and Destructor
The constructor is a special method that is implemented when an object of a particular class is created.
Constructor is also useful for creating and setting default values for a new object of a data member.
13
To create a class without defining a constructor, the compiler automatically creates a default
constructor. In this way, there is a constructor that is always available in every class. Furthermore, we can
create more than one constructor in a class with the use of New keyword but with the different parameters,
and it does not return anything.
Default Constructor: to create a constructor without defining an argument, it is called a default
constructor.
Syntax
Public Class MyClass
' Creates a Constructor using the New
Public Sub New()
'Statement to be executed
End Sub
End Class
Parameterized Constructor
To pass one or more arguments to a constructor, the constructor is known as a parameterized
constructor. And the object of the class should be initialized with arguments when it is created.
Destructor
Destructor is a special function that is used to destroy a class object when the object of the class goes
out of scope. It can be represented as the Finalize() method and does not accept any parameter nor return any
value. Furthermore, it can be called automatically when a class object is not needed.
Destructor Syntax
Destructor using the Finalize() method in [Link].
Class My_Destructor
' define the destructor
Protected Overrides Sub Finalize()
' Statement or code to be executed
End Sub
End Class

Multithreading
Thread
When two or more processes execute simultaneously in a program, the process is known as
multithreading. And the execution of each process is known as the thread. A single thread is used to execute
a single logic or task in an application. By default, each application has one or more threads to execute each
process, and that thread is known as the main thread.
To create and access a new thread in the Thread class, we need to import
the [Link] namespace. When the execution of a program begins in [Link], the Main thread is
automatically called to handle the program logic. And if we create another thread to execute the process in
Thread class, the new thread will become the child thread for the main thread.
Create a new Thread
To create a thread by extending the Thread class and pass the ThreadStart delegate as an argument to
the Thread constructor. A ThreadStart() is a method executed by the new thread. We need to call
the Start() method to start the execution of the new thread because it is initially in the unstart state. And the
PrintInfo parameter contains an executable statement that is executed when creating a new thread
Create a new thread
Dim th As Thread = New Thread( New ThreadStart(PrintInfo)
' Start the execution of newly thread
[Link]()
Thread Methods
The following are the most commonly used methods of Thread class.
14
Method Description

Abort() As the name defines, it is used to terminate the execution of a thread.

AllocateDataSlot() It is used to create a slot for unnamed data on all threads.

AllocateNamedDatsSlot() It is used to create a slot for defined data on all threads.

Equals() It is used to check whether the current and defined thread object are equal.

Interrupt() It is used to interrupt a thread from the Wait, sleep, and join thread state.

Join() It is a synchronization method that stops the calling thread until the
execution thread completes.

Resume() As the name suggests, a Resume() method is used to resume a thread that
has been suspended.

Sleep() It is used to suspend the currently executing thread for a specified time.

Start() It is used to start the execution of thread or change the state of an ongoing
instance.

Suspend() It is used to stop the currently executing thread.


Thread Life Cycle
Multithreading, each thread has a life cycle that starts when a new object is created using the Thread
Class. Once the task defined by the thread class is complete, the life cycle of a thread will get the end
There are some states of thread cycle in [Link] programming.

State Description

Unstarted When we create a new thread, it is initially in an unstarted state.

Runnable When we call a Start() method to prepare a thread for running, the runnable situation
occurs.

Running A Running state represents that the current thread is running.

Not It indicates that the thread is not in a runnable state, which means that the thread in
Runnable sleep() or wait() or suspend() or is blocked by the I/O operation.

Dead If the thread is in a dead state, either the thread has been completed its work or aborted
Multithreading
When two or more processes are executed in a program to simultaneously perform multiple tasks, the
process is known as multithreading. To execute an application, the Main thread will automatically be called
to execute the programming logic synchronously, which means it executes one process after another. In this
way, the second process has to wait until the first process is completed, and it takes time

15
Message Queuing (MSMQ)
Message Queuing (MSMQ) technology enables applications running at different times to
communicate across heterogeneous networks and systems that may be temporarily offline. Applications send
messages to queues and read messages from queues. The following illustration shows how a queue can hold
messages that are generated by multiple sending applications and read by multiple receiving applications.

It can be used to implement solutions to both asynchronous and synchronous scenarios requiring high
performance. The following list shows several places where Message Queuing can be used.
 Mission-critical financial services: for example, electronic commerce.
 Embedded and hand-held applications: for example, underlying communications to and from embedded
devices that route baggage through airports by means of an automatic baggage system.
 Outside sales: for example, sales automation applications for traveling sales representatives.
 Workflow: Message Queuing makes it easy to create a workflow that updates each system. A typical
design pattern is to implement an agent to interact with each system. Using a workflow-agent
architecture also minimizes the impact of changes in one system on the other systems. With Message
Queuing, the loose coupling between systems makes upgrading individual systems simpler.
Programming MSMQ
The concepts of MSMQ programming like creating a queue, writing a message to the queue and receiving
from it etc.

They are two applications: a sending application and a receiving application.


1. The sending application prepares a message and puts it into a queue. A message can be any piece of
information that the receiving application understands.
2. The receiving application receives the message from the queue and processes it. One thing to note
here is that the sender and the receiver are not tightly coupled and they can work without the other
application being online.

16
Enter [Link]
To build a messaging application we need to create a queue first, have one application send messages
to it and have another application receive those messages from it.
The basic types of MSMQ queues: Private and Public. Public queues are those that are published in
the active directory. So, applications running on different servers throughout the network can find and
use public queues through the active directory. Private queues on the other hand are available locally on a
particular machine and are not published in the active directory.
The [Link] namespace provides a set of classes which can be used to work with MSMQ.
The MessageQueue class provides all the necessary functionality to work with and manipulate MSMQ
queues. It is like a wrapper around message queuing. The Message class provides everything required to
define and use an MSMQ message.
Creating a Queue
Queues can be created either programmatically or through the computer management snap-in. I
presume MSMQ is installed on your system.
Programmatically
The Create shared method of the MessageQueue class to create a queue. In the code snippet given
below I am creating a private queue named MyNewQueue.
Try
Dim queueAsMessageQueue
queue = [Link](".\Private$\MyNewQueue")
' If there is an error creating a queue you get a MessageQueueException exception
Catch ex As MessageQueueException
End Try
Note the parameter I have passed to the the Create method. It is called the path of the queue. The single dot (.)
in the path indicates the queue is created on the local machine. Since we are creating a private queue here, we
need to include a Private$ in the path. If we are creating or accessing a public queue we can just use
the MachineName\QueueName format in the path.
Through the computer management snap-in
1. Open the computer management snap-in.
2. Navigate to the [Message Queuing] node under the Services and Applications section.
3. Right click on the [Private Queues] and in the context menu that appears select New -> Private Queue. Public
queues can be created in a similar fashion

17
Sending a simple message
The Send method of the MessageQueue object to post a message to the queue.
[Link]("<<Message>>", "<<Message Label>>")
This can be a Message object or any managed object. If the object is not of type Message, then the object is
serialized and stored in the message body.
Reading a message from the queue
There are two types of operations with respect to reading a message from the Queue: Peeking and
Receiving.
1. Receive a message from the queue, the message is removed from the queue.
2. Peeking is similar to Receiving but here the message is not removed from the queue.
Dim msg As Message
msg = [Link]()
[Link]([Link])

There are many overloads of Receive and the one used above indefinitely blocks the caller till
a message is available on the queue. To do not want to get blocked indefinitely.
The overload of Receive which takes a TimeSpan argument and this throws an exception if a message
is not received within that time span. Here is a call to receive which times out after 1000 ticks (1 second).
msg = [Link](New TimeSpan(1000))
Peek and Receive operations are synchronous in nature. However there exists a method where we can do
these operations asynchronously.
The BeginPeek and EndPeek or BeginReceive or EndReceive respectively.

Deleting a Queue
The Delete shared method of the MessageQueue object to delete a queue from the system.

18
[Link](".\Private$\MyNewQueue")
[Link](".\Private$\MyNewQueue")

Other simple queue operations


Enlisted below are some other simple operations on a queue.
Purge Deletes all the messages contained in the queue.
GetAllMessages Returns all the messages that are in the queue.
GetPrivateQueuesByMachine Retrieves all the private queues on the specified computer.
Determines whether a Message Queuing queue at the specified
Exists
path exists.
GetMessageEnumerator Creates an enumerator object for all the messages in the queue.
Gets or sets the formatter used to serialize an object into or
Formatter deserialize an object from the body of a message read from or
written to the queue.

19

You might also like