SlideShare a Scribd company logo
ArguS academy V.B-PART-IV 
Page 1 
Events and Delegates 
Events and Event Handling 
Events are action that triggered either by a user action, program logic or by the system. 
Whenever an event occurs, the user may either ignore the event or deal with the event with the help of a suitable code. Good programming technique implies that we take care of events by placing appropriate codes in our programs that will execute whenever the event takes place. Procedures containing codes that will process the event are called event handlers. 
Module m12 
Public Event UserLoggedout(ByVal Loginname as string) 
Sub checkstatus() 
RaiseEvent UserLoggedout(“Catherine”) 
End sub 
Public sub onCheckStatus(name as string) 
System.Console.WriteLine(name & “has looged out !!”) 
End sub 
Sub main() 
AddHandler m.UserLoggedout,Addressof onChechStatus 
checkStatus() 
end sub 
end module 
Handles 
The Handles keyword is used to declare that a particular procedure will handle a specific event. By using Handles keywords with a procedure declaration, we can enable the procedure to handle events that were raised by an object variable declared using the WithEvent keyword. The withEvents statement and Handles clause provide a declarative way of specifying event handlers. 
Class x 
Public event A 
Public sub test() 
RaiseEvent A 
End sub 
End class 
Module m 
Dim withEvents obj as x 
Public sub main() 
Obj= new x() 
Obj.Test() 
End sub 
Public sub OurHandler Handles obj.A 
System.Console.WriteLine(“Event is being handled ”) 
End sub 
End module 
Delegates 
The term delegates is defined as a representative of a country, organization or another person. In VB. Net, a delegate is defined as a representative of a function or a procedure. It holds a reference to a method. 
A delegate declaration must specify the parameters and / or the return type for the method which it represents. 
VB. Net allows us to create two type of Delegate classes – single cast delegates and multi cast delegates. Single cast delegates are delegate classes that are derived from the Delegate class. Multicast delegates are derived from the Multicast Delegate class. These delegates typically have an invocation list or linked list of delegates that are executed when the invoke method is called. 
Single cast delegates contain invocation lists with only one method, whereas multicast delegates contain invocation lists with more than one method. 
Delegate function isdivisible(n as integer) 
Module m 
Public function check (I as integer) 
If I mod 5 = 0 then 
System.Console.WriteLine(“Divisible ”) 
Else 
System.Console.WriteLine(“not Divisible”) 
End if 
End function 
Public sub main() 
Dim x as indivisible
ArguS academy V.B-PART-IV 
Page 2 
X=addressof check 
X(11) 
End sub 
End module 
Events and Delegates 
The VB.Net event model is to a large extend based on delegates. The event model makes use of delegates to bind method used to handle them. A delegates can be bound 
At run time to any method whose signature list matches that of the event handler, thus making it very dynamic. 
Delegate sub isdivisible(n as Integer) 
Module m 
Public event a as isdivisible 
Sub fire(I as integer) 
If I mod 5=0 then 
System.Console.WriteLine(“Divisible”) 
Else 
System.Console.WriteLine(“not Divisible”) 
End if 
End sub 
Public sub main() 
Addhandler a, (Addressof fire) 
m.aEvent(13) 
end sub 
end module 
Inheriting event 
A derived class inherits events from its base class. It is perfectly valid to write a separate handler for the event in the derived class. This can be done using the Handles keyword with the MyBase keyword followed by the event name. 
Class x 
Public event p 
Public sub test() 
RaiseEvent p 
End sub 
End class 
Class y 
Inherits x 
Public sub DerivedHandler Handles MyBase.p 
System.Console.WriteLine(“Base class Event is being handled in derived class”) 
End sub 
End class 
Module m 
Dim withEvents obj as y 
Public sub main() 
obj = new y() 
obj.Test() 
end sub 
end module 
Multithreading and Garbage Collection 
Multithreading 
Multithreading is the ability of a single program to perform more than one task at the same time. 
A thread is the smallest unit of executable code that performs a particular task. An application can be divided into multiple tasks and each task can be assigned to a thread. Two or more threads can be executed simultaneously. This is called multithreading. Let us take the simple instance of a game simulator. The program plays audio sounds, displays graphics and determines scores – all at the same time. This can be considered as a threaded application. Each task is a thread and all threads are executed simultaneously 
Multithreading in VB.Net is accomplished primarily through the classes and interface in the System.Threading namespace. To create a new thread, we pass a delegate to the constructor of the System.Threading Thread class. This delegate must point to a method that will act as starting point for the thread. 
Dim t as new System.Threading.Thread(AddressOf DoAction) 
Here AddressOf DoAction is the delegate and DoAction is the start method for the thread. 
The thread can then be instantiated with the help of the start method as follows 
t.start()
ArguS academy V.B-PART-IV 
Page 3 
Module m 
Public sub DoAction() 
Dim i as Integer=1 
While true 
System.Console.WriteLine(i) 
System.Console.WriteLine(“Thread is running ”) 
i=i+1 
end while 
end sub 
public sub main() 
dim t as new System.Threading.Thread(AddressOf DoAction) 
t.start() 
end sub 
end module 
Declares a DoAction() method that will serve as the starting point for the thread. This method declares an integer variable and prints the incremented value of this variable each time within an infinite loop. 
Sleep method 
Module m 
Public sub DoAction() 
Dim i as integer=1 
While true 
System.Console.WriteLine(i) 
System.Console.WriteLine(“Thread is running”) 
System.Threading.Thread.sleep(400) 
i=i+1 
end while 
end sub 
public sub main() 
dim t as new System.Threading.Thread(AddressOf DoAction) 
t.Start() 
end sub 
end module 
The suspend() method of the System.Threading.Thread class is used to suspend the action of a thread for an indefinite period. The thread can be resumed using the Resume() method. 
Module m1 
Dim t1 as new System.Threading.Thread(Addressof DoAction) 
Dim t2 as new System.Threading.Thread(Addressof DoAction) 
Public sub DoAction() 
Dim I as integer=1 
While true 
System.Console.WriteLine(i) 
i=i+1 
if i=4 then 
System.Console.WriteLine(“t1 is now going to be suspended ”) 
System.Threading.Thread.CurrentThread.Suspend() 
End if 
System.Threading.Thread.sleep(200) 
End while 
End sub 
Public sub DoAction2() 
Dim j as integer=100 
While true 
System.Console.WriteLine(j) 
System.Threading.Thread.Sleep(200) 
End while 
End sub 
Public sub main() 
t1.Start() 
t2.Start() 
end sub 
end module
ArguS academy V.B-PART-IV 
Page 4 
Synchronization 
When two or more threads in a multithread application access a common method or data simultaneously, there will be conflict and as a result vital information could be lost or data will become inconsistent. To avoid this, it is necessary to have some kind of mechanism in a multithreaded application that allows the methods or data to be accessed by one thread at a time. Synchronization is a process that allows threads to access methods or data one thread at a time. 
Module m 
Dim a1 as new A() 
Dim a2 as new A() 
Dim t1 as new System.Threading.Thread(AddressOf a1.Test) 
Dim t2 as new System.Threading.Thread(AddressOf a2.Test) 
Public i as integer =1 
Public sub main() 
t1.Start() 
t2.Start() 
end sub 
end module 
class A 
public sub Test() 
while true 
System.Console.WriteLine(i) 
i=i+1 
System.Threading.Thread.Sleep(200) 
End while 
End sub 
End class 
Memory Management and Garbage Collection 
Applications need to use various types of resources such as network connections, Database connections and memory buffers. These applications require the memory to be reversed for usage by resources and at the end of the application the memory needs to be resealed in order to prevent the memory overflow. Memory management in earlier programming languages had to be carried out manually. Unused resources had to be released by writing cumbersome code. This process was very tedious and time consuming. However, recent programming languages use eliminates common errors that arise from manual methods of memory management. In an automatic memory management environment, a garbage collector program runs as a separate thread every now and then. The garbage collector frees memory that is no longer needed. 
VB.NET uses a garbage collector to implement automatic memory management. 
Finalize and Dispose methods 
Earlier we have discussed that destructors in VB.NET are implemented by overriding the finalize() method. Cleanup operations such as releasing memory that is no longer in use and closing data base connections and files may be placed in destructor so that whenever an object goes out of scope, memory management is per formed. To reclaim each object that has a finalize() method, VB.NET will need to perform two cycles of garbage collections and this will lead to lower performance. This is because when the garbage collector performs a garbage collection, it reclaims memory for unused objects that do not have a finalize() method. For those object s that have finalize() method, it places their entries in a list of objects marked as ready for finalization. It then performs garbage collection later for these objects and finally destroys them. To avoid this, finalize() method should be used efficiently. 
Ex.-1 
Class x 
Public sub new 
System.Console.WriteLine(“Constructor”) 
End sub 
Protected Override sub Finalize 
System.Console.WriteLine(“Destructor”) 
End sub 
End class 
Module m 
Sub main() 
Dim a as new x 
A=Nothiong 
System.console.WriteLine(“End of Main”) 
End sub 
End module 
Ex=II 
Module m 
Sub main
ArguS academy V.B-PART-IV 
Page 5 
Dim a as new x 
A=Nothing 
System.GC.collection() 
System.GC.WaitPendingFinalizers() 
System.Console.WriteLine(“End of Main”) 
End sub 
End module 
Class x 
Public sub new 
System.Console.WriteLine(“Constructor”) 
End sub 
Protected Overrides sub Finalize 
System.Console.WritelINE(“Destructors”) 
End sub 
End class 
Working with Database Using VB. Net 
Universal Data Access 
With respect to data access, application scenario today has two emerging needs. They are: 
1. Accessing legacy data or information that is stored in an organization in different formats in various types of systems. 
2. Accessing non relational data. 
The need of the hour is to have a single high-performance framework or model with the help of which applications can connect to various database products without changing the entire code. 
Universal Data Access OR UDA is one such framework which application programs use to connect to database from various database venders through a single interface. 
Managed Data Providers 
A managed data provider is a set of software programs that allows access to databases by providing an interface that performs database related operations on behalf of the application. 
 Establish a connection to the database 
 Execute commands and retrieve result 
 Execute commands and update data. 
Connection – Used to establish a connection to the database. 
Command: Carries out operation while connected to the database. 
Introduction to ADO.NET 
Traditionally, an application maintained database connection as long as it executed. This is not feasible as open connection consume valuable resources. Also, performance is reduced because of the overheads in maintaining connection. 
ADO.NET is a data object model that lets us work with databases version of ADO designed for the .Net framework. Data access in ADO.Net is based on disconnected architecture. This means that the connection need not be maintained continuously while the application is executing. The application connects to the database as and when it need to retrieve and update data. 
Advantages offered by ADO.Net are summarized below: 
 Maintainability: It is difficult to increase the number of application tiers within an application after the application has been deployed. However, if the application is implemented using ADO.Net then increasing the number of tiers becomes a very easy process. 
 Programmability: Data classes in ADO.Net result in typed dataset and thus allows us to access data through typed programming. This marks code easier to read, write and debug. It is also safer because it provides for type checking at compile at compile time. 
 Performance: As stated earlier, Ado.NET works with disconnected architecture. This increases performance. 
 Interoperability : Since ADO.Net makes extensive use of XML, interoperability becomes very simple using ADO.Net 
Command Object 
The Command objects are used to retrieve and manipulate data. For this purpose, sqlDataAdapter and OleDbAdapter class are defined in the System.Data.SqlClient and System.Data.OleDb namespace respectively;
ArguS academy V.B-PART-IV 
Page 6 
DataSet 
While working with database, applications often need to fetch sets of data repeatedly. In a disconnected architecture it is not feasible for the application to go back to the database every time data needs to be fetched. It is much more feasible to have a temporary storage of records from where the application can fetch data whenever needs. A dataset is one such temporary storage. It is a cache of records fetched from the database. The dataset class in the System.Data namespace is the main building block of 
Imports Microsoft.visualbasic 
Imports System 
Imports System.data 
Imports System.XML 
Module m 
Sub Main() 
Dim myconn As new 
Data.SqlClient.SqlConnection (“server=Ritchasqldb;database=EmpDep;uid=sa;password=passwd;”) 
Myconn.open() 
Dim adap As New Data.SqlClient.SqlDataAdapter(s, myconn) 
Dim dataset As Data. Dataset=New Data.dataSet() 
Adap.fill(dataset, “details”) 
Dimtbl as datatable= dataset.tables(“details”) 
Dim dr As DataRow 
Dim I As DataRow 
Dim j As Datacolumn 
For Each I In tbl.Rows 
For Each j In tbl.columns 
System.Console.Write((i(j).ToString()).PadRight(15,””)) 
Next 
System.Console.WriteLine(“”) 
Next 
Myconn.close() 
End Sub 
End Module 
We create a database connection usi9ng the SqlConnection class. We pass the name of the database server, the name of the database and pass it an SQL command along with the connection name. The SQL command retrieves all the records from the department table. We fill the results of this command into a dataset and extract the dataset rows and columns using a nested for loop. We print each of these details on the console within the nested for loop. In order to format the data while printing. We use the PadRight() function to include appropriate spaces in-between the columns. Finally, when all the records have been retrieved and printed, we close the connection.

More Related Content

PDF
Intake 38 5
PDF
Intake 38 data access 5
PPT
Java căn bản - Chapter7
PPT
Chapter 7 - Defining Your Own Classes - Part II
PPT
Chapter 2 - Getting Started with Java
PDF
Intake 38 5 1
PDF
Intake 38 3
PDF
Intake 37 4
Intake 38 5
Intake 38 data access 5
Java căn bản - Chapter7
Chapter 7 - Defining Your Own Classes - Part II
Chapter 2 - Getting Started with Java
Intake 38 5 1
Intake 38 3
Intake 37 4

What's hot (20)

PPTX
C# Generics
PDF
Intake 38 data access 3
PDF
Intake 37 6
PPTX
.NET F# Events
PPTX
Chap2 class,objects
PDF
Intake 38 4
PDF
Intake 37 2
PDF
C# Delegates and Event Handling
PDF
Wrapper classes
PDF
Intake 38 2
PPTX
Evolution of C# delegates
PPT
Call Back
PDF
Intake 38 12
DOC
CS2309 JAVA LAB MANUAL
PPTX
Icom4015 lecture10-f16
PPT
Executing Sql Commands
PPT
Pertemuan 6-2-sequence-diagram
PDF
Built in classes in java
PDF
Intake 37 1
PPTX
Java Foundations: Methods
C# Generics
Intake 38 data access 3
Intake 37 6
.NET F# Events
Chap2 class,objects
Intake 38 4
Intake 37 2
C# Delegates and Event Handling
Wrapper classes
Intake 38 2
Evolution of C# delegates
Call Back
Intake 38 12
CS2309 JAVA LAB MANUAL
Icom4015 lecture10-f16
Executing Sql Commands
Pertemuan 6-2-sequence-diagram
Built in classes in java
Intake 37 1
Java Foundations: Methods
Ad

Similar to Vb.net iv (20)

PDF
PPTX
C# Delegates
PPTX
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PPTX
Learn VB.NET at ASIT
PPTX
Visual Basic –User Interface- V
PPTX
Delegates and events
PPT
Introduction to VB.Net By William Lacktano.ppt
PPTX
Advanced programming topics asma
PPT
VB.net
PDF
Introduction to Visual Basic 6.0
PDF
Vb net1
PDF
Vb.net iii
PDF
Vb.net ii
PPTX
Visual Basic User Interface -IV
PDF
Bt0082 visual basic
PPTX
Delegates and events
PPTX
VB.net&OOP.pptx
PPS
Vb net xp_04
PPS
Vb.net session 04
PPTX
Interface
C# Delegates
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
Learn VB.NET at ASIT
Visual Basic –User Interface- V
Delegates and events
Introduction to VB.Net By William Lacktano.ppt
Advanced programming topics asma
VB.net
Introduction to Visual Basic 6.0
Vb net1
Vb.net iii
Vb.net ii
Visual Basic User Interface -IV
Bt0082 visual basic
Delegates and events
VB.net&OOP.pptx
Vb net xp_04
Vb.net session 04
Interface
Ad

More from argusacademy (20)

PPSX
Css & dhtml
PPSX
Html table
PPSX
Html ordered & unordered list
PPSX
Html level ii
PPSX
Html frame
PPSX
Html forms
PPSX
Html creating page link or hyperlink
PPSX
Html basic
PPSX
Java script
PPSX
Php string
PPSX
Php session
PPSX
Php opps
PPSX
Php oops1
PPSX
Php if else
PPSX
Php creating forms
PPSX
Php create and invoke function
PPSX
Php basic
PPSX
Php array
PPSX
Sql query
PPSX
Css & dhtml
Html table
Html ordered & unordered list
Html level ii
Html frame
Html forms
Html creating page link or hyperlink
Html basic
Java script
Php string
Php session
Php opps
Php oops1
Php if else
Php creating forms
Php create and invoke function
Php basic
Php array
Sql query

Recently uploaded (20)

PDF
Sports Quiz easy sports quiz sports quiz
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Pre independence Education in Inndia.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Institutional Correction lecture only . . .
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Classroom Observation Tools for Teachers
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Lesson notes of climatology university.
PPTX
Pharma ospi slides which help in ospi learning
PDF
RMMM.pdf make it easy to upload and study
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Sports Quiz easy sports quiz sports quiz
STATICS OF THE RIGID BODIES Hibbelers.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Pre independence Education in Inndia.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Cell Types and Its function , kingdom of life
Supply Chain Operations Speaking Notes -ICLT Program
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Institutional Correction lecture only . . .
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Classroom Observation Tools for Teachers
TR - Agricultural Crops Production NC III.pdf
Lesson notes of climatology university.
Pharma ospi slides which help in ospi learning
RMMM.pdf make it easy to upload and study
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...

Vb.net iv

  • 1. ArguS academy V.B-PART-IV Page 1 Events and Delegates Events and Event Handling Events are action that triggered either by a user action, program logic or by the system. Whenever an event occurs, the user may either ignore the event or deal with the event with the help of a suitable code. Good programming technique implies that we take care of events by placing appropriate codes in our programs that will execute whenever the event takes place. Procedures containing codes that will process the event are called event handlers. Module m12 Public Event UserLoggedout(ByVal Loginname as string) Sub checkstatus() RaiseEvent UserLoggedout(“Catherine”) End sub Public sub onCheckStatus(name as string) System.Console.WriteLine(name & “has looged out !!”) End sub Sub main() AddHandler m.UserLoggedout,Addressof onChechStatus checkStatus() end sub end module Handles The Handles keyword is used to declare that a particular procedure will handle a specific event. By using Handles keywords with a procedure declaration, we can enable the procedure to handle events that were raised by an object variable declared using the WithEvent keyword. The withEvents statement and Handles clause provide a declarative way of specifying event handlers. Class x Public event A Public sub test() RaiseEvent A End sub End class Module m Dim withEvents obj as x Public sub main() Obj= new x() Obj.Test() End sub Public sub OurHandler Handles obj.A System.Console.WriteLine(“Event is being handled ”) End sub End module Delegates The term delegates is defined as a representative of a country, organization or another person. In VB. Net, a delegate is defined as a representative of a function or a procedure. It holds a reference to a method. A delegate declaration must specify the parameters and / or the return type for the method which it represents. VB. Net allows us to create two type of Delegate classes – single cast delegates and multi cast delegates. Single cast delegates are delegate classes that are derived from the Delegate class. Multicast delegates are derived from the Multicast Delegate class. These delegates typically have an invocation list or linked list of delegates that are executed when the invoke method is called. Single cast delegates contain invocation lists with only one method, whereas multicast delegates contain invocation lists with more than one method. Delegate function isdivisible(n as integer) Module m Public function check (I as integer) If I mod 5 = 0 then System.Console.WriteLine(“Divisible ”) Else System.Console.WriteLine(“not Divisible”) End if End function Public sub main() Dim x as indivisible
  • 2. ArguS academy V.B-PART-IV Page 2 X=addressof check X(11) End sub End module Events and Delegates The VB.Net event model is to a large extend based on delegates. The event model makes use of delegates to bind method used to handle them. A delegates can be bound At run time to any method whose signature list matches that of the event handler, thus making it very dynamic. Delegate sub isdivisible(n as Integer) Module m Public event a as isdivisible Sub fire(I as integer) If I mod 5=0 then System.Console.WriteLine(“Divisible”) Else System.Console.WriteLine(“not Divisible”) End if End sub Public sub main() Addhandler a, (Addressof fire) m.aEvent(13) end sub end module Inheriting event A derived class inherits events from its base class. It is perfectly valid to write a separate handler for the event in the derived class. This can be done using the Handles keyword with the MyBase keyword followed by the event name. Class x Public event p Public sub test() RaiseEvent p End sub End class Class y Inherits x Public sub DerivedHandler Handles MyBase.p System.Console.WriteLine(“Base class Event is being handled in derived class”) End sub End class Module m Dim withEvents obj as y Public sub main() obj = new y() obj.Test() end sub end module Multithreading and Garbage Collection Multithreading Multithreading is the ability of a single program to perform more than one task at the same time. A thread is the smallest unit of executable code that performs a particular task. An application can be divided into multiple tasks and each task can be assigned to a thread. Two or more threads can be executed simultaneously. This is called multithreading. Let us take the simple instance of a game simulator. The program plays audio sounds, displays graphics and determines scores – all at the same time. This can be considered as a threaded application. Each task is a thread and all threads are executed simultaneously Multithreading in VB.Net is accomplished primarily through the classes and interface in the System.Threading namespace. To create a new thread, we pass a delegate to the constructor of the System.Threading Thread class. This delegate must point to a method that will act as starting point for the thread. Dim t as new System.Threading.Thread(AddressOf DoAction) Here AddressOf DoAction is the delegate and DoAction is the start method for the thread. The thread can then be instantiated with the help of the start method as follows t.start()
  • 3. ArguS academy V.B-PART-IV Page 3 Module m Public sub DoAction() Dim i as Integer=1 While true System.Console.WriteLine(i) System.Console.WriteLine(“Thread is running ”) i=i+1 end while end sub public sub main() dim t as new System.Threading.Thread(AddressOf DoAction) t.start() end sub end module Declares a DoAction() method that will serve as the starting point for the thread. This method declares an integer variable and prints the incremented value of this variable each time within an infinite loop. Sleep method Module m Public sub DoAction() Dim i as integer=1 While true System.Console.WriteLine(i) System.Console.WriteLine(“Thread is running”) System.Threading.Thread.sleep(400) i=i+1 end while end sub public sub main() dim t as new System.Threading.Thread(AddressOf DoAction) t.Start() end sub end module The suspend() method of the System.Threading.Thread class is used to suspend the action of a thread for an indefinite period. The thread can be resumed using the Resume() method. Module m1 Dim t1 as new System.Threading.Thread(Addressof DoAction) Dim t2 as new System.Threading.Thread(Addressof DoAction) Public sub DoAction() Dim I as integer=1 While true System.Console.WriteLine(i) i=i+1 if i=4 then System.Console.WriteLine(“t1 is now going to be suspended ”) System.Threading.Thread.CurrentThread.Suspend() End if System.Threading.Thread.sleep(200) End while End sub Public sub DoAction2() Dim j as integer=100 While true System.Console.WriteLine(j) System.Threading.Thread.Sleep(200) End while End sub Public sub main() t1.Start() t2.Start() end sub end module
  • 4. ArguS academy V.B-PART-IV Page 4 Synchronization When two or more threads in a multithread application access a common method or data simultaneously, there will be conflict and as a result vital information could be lost or data will become inconsistent. To avoid this, it is necessary to have some kind of mechanism in a multithreaded application that allows the methods or data to be accessed by one thread at a time. Synchronization is a process that allows threads to access methods or data one thread at a time. Module m Dim a1 as new A() Dim a2 as new A() Dim t1 as new System.Threading.Thread(AddressOf a1.Test) Dim t2 as new System.Threading.Thread(AddressOf a2.Test) Public i as integer =1 Public sub main() t1.Start() t2.Start() end sub end module class A public sub Test() while true System.Console.WriteLine(i) i=i+1 System.Threading.Thread.Sleep(200) End while End sub End class Memory Management and Garbage Collection Applications need to use various types of resources such as network connections, Database connections and memory buffers. These applications require the memory to be reversed for usage by resources and at the end of the application the memory needs to be resealed in order to prevent the memory overflow. Memory management in earlier programming languages had to be carried out manually. Unused resources had to be released by writing cumbersome code. This process was very tedious and time consuming. However, recent programming languages use eliminates common errors that arise from manual methods of memory management. In an automatic memory management environment, a garbage collector program runs as a separate thread every now and then. The garbage collector frees memory that is no longer needed. VB.NET uses a garbage collector to implement automatic memory management. Finalize and Dispose methods Earlier we have discussed that destructors in VB.NET are implemented by overriding the finalize() method. Cleanup operations such as releasing memory that is no longer in use and closing data base connections and files may be placed in destructor so that whenever an object goes out of scope, memory management is per formed. To reclaim each object that has a finalize() method, VB.NET will need to perform two cycles of garbage collections and this will lead to lower performance. This is because when the garbage collector performs a garbage collection, it reclaims memory for unused objects that do not have a finalize() method. For those object s that have finalize() method, it places their entries in a list of objects marked as ready for finalization. It then performs garbage collection later for these objects and finally destroys them. To avoid this, finalize() method should be used efficiently. Ex.-1 Class x Public sub new System.Console.WriteLine(“Constructor”) End sub Protected Override sub Finalize System.Console.WriteLine(“Destructor”) End sub End class Module m Sub main() Dim a as new x A=Nothiong System.console.WriteLine(“End of Main”) End sub End module Ex=II Module m Sub main
  • 5. ArguS academy V.B-PART-IV Page 5 Dim a as new x A=Nothing System.GC.collection() System.GC.WaitPendingFinalizers() System.Console.WriteLine(“End of Main”) End sub End module Class x Public sub new System.Console.WriteLine(“Constructor”) End sub Protected Overrides sub Finalize System.Console.WritelINE(“Destructors”) End sub End class Working with Database Using VB. Net Universal Data Access With respect to data access, application scenario today has two emerging needs. They are: 1. Accessing legacy data or information that is stored in an organization in different formats in various types of systems. 2. Accessing non relational data. The need of the hour is to have a single high-performance framework or model with the help of which applications can connect to various database products without changing the entire code. Universal Data Access OR UDA is one such framework which application programs use to connect to database from various database venders through a single interface. Managed Data Providers A managed data provider is a set of software programs that allows access to databases by providing an interface that performs database related operations on behalf of the application.  Establish a connection to the database  Execute commands and retrieve result  Execute commands and update data. Connection – Used to establish a connection to the database. Command: Carries out operation while connected to the database. Introduction to ADO.NET Traditionally, an application maintained database connection as long as it executed. This is not feasible as open connection consume valuable resources. Also, performance is reduced because of the overheads in maintaining connection. ADO.NET is a data object model that lets us work with databases version of ADO designed for the .Net framework. Data access in ADO.Net is based on disconnected architecture. This means that the connection need not be maintained continuously while the application is executing. The application connects to the database as and when it need to retrieve and update data. Advantages offered by ADO.Net are summarized below:  Maintainability: It is difficult to increase the number of application tiers within an application after the application has been deployed. However, if the application is implemented using ADO.Net then increasing the number of tiers becomes a very easy process.  Programmability: Data classes in ADO.Net result in typed dataset and thus allows us to access data through typed programming. This marks code easier to read, write and debug. It is also safer because it provides for type checking at compile at compile time.  Performance: As stated earlier, Ado.NET works with disconnected architecture. This increases performance.  Interoperability : Since ADO.Net makes extensive use of XML, interoperability becomes very simple using ADO.Net Command Object The Command objects are used to retrieve and manipulate data. For this purpose, sqlDataAdapter and OleDbAdapter class are defined in the System.Data.SqlClient and System.Data.OleDb namespace respectively;
  • 6. ArguS academy V.B-PART-IV Page 6 DataSet While working with database, applications often need to fetch sets of data repeatedly. In a disconnected architecture it is not feasible for the application to go back to the database every time data needs to be fetched. It is much more feasible to have a temporary storage of records from where the application can fetch data whenever needs. A dataset is one such temporary storage. It is a cache of records fetched from the database. The dataset class in the System.Data namespace is the main building block of Imports Microsoft.visualbasic Imports System Imports System.data Imports System.XML Module m Sub Main() Dim myconn As new Data.SqlClient.SqlConnection (“server=Ritchasqldb;database=EmpDep;uid=sa;password=passwd;”) Myconn.open() Dim adap As New Data.SqlClient.SqlDataAdapter(s, myconn) Dim dataset As Data. Dataset=New Data.dataSet() Adap.fill(dataset, “details”) Dimtbl as datatable= dataset.tables(“details”) Dim dr As DataRow Dim I As DataRow Dim j As Datacolumn For Each I In tbl.Rows For Each j In tbl.columns System.Console.Write((i(j).ToString()).PadRight(15,””)) Next System.Console.WriteLine(“”) Next Myconn.close() End Sub End Module We create a database connection usi9ng the SqlConnection class. We pass the name of the database server, the name of the database and pass it an SQL command along with the connection name. The SQL command retrieves all the records from the department table. We fill the results of this command into a dataset and extract the dataset rows and columns using a nested for loop. We print each of these details on the console within the nested for loop. In order to format the data while printing. We use the PadRight() function to include appropriate spaces in-between the columns. Finally, when all the records have been retrieved and printed, we close the connection.