Monday, April 28, 2008

Thread

The process of creating a thread is called spawning a new thread, the process of destroying an existing thread is called killing or terminating a thread, and the process of pausing a thread is called putting the thread to sleep.

A short-lived thread is a thread that is created to perform a single task and is then terminated. It is common to create short-lived threads to perform operating system tasks such as copying or moving files. In such situations, you can use the ThreadPool class in the .NET Framework. This class can also be used when it is not necessary to have full control over each individual thread.

The ThreadPool class manages a set of readily available threads to be used by a process. Each process has only one thread pool that the process uses to execute different methods. Resource allocation does not need to occur every time a thread is started because the thread is already created in the pool. This increases application performance. However, there are situations in which the thread pool should be avoided because there is no direct control over the thread. You should not use a thread pool when:
You require a foreground thread.
You require a thread to have a particular priority.
You have tasks that can block threads for long periods of time. The thread pool has a maximum number of threads, so a large number of threads from the thread pool being blocked might prevent tasks from starting.
You need to place threads into a single-threaded apartment. All thread pool threads are in the multithreaded apartment.
You need to have a stable identity associated with the thread, or you need to dedicate a thread to a task.
Based on these situations, you need to use a thread pool whenever the application requires threads to execute short-lived tasks in a fast-paced scenario. For example, if you want to test read/write operations to a database simulating a multiuser environment, you can create a set of methods that access the database by executing common queries, and use multiple threads from the thread pool to execute the methods multiple times, simultaneously.


There is a limit of 25 threads in a thread pool; therefore, even if you start 50 threads, only 25 threads will be executed at a given time. As soon as a thread finishes, another thread that was waiting for an idle thread in the pool can start.

The process of managing access to resources being shared by multiple threads is called synchronization.Synchronization comprises of locking mechanisms, signaling, and some interlocked operations.

the most common ones include exclusive and shared locks. The .NET Framework provides several classes that you can use to lock resources. However, the simplest method to lock a shared resource is to use the SyncLock statement in Visual Basic or the lock statement in C#.
When a thread notifies another thread about the lock status of a resource, it is called signaling. synchronization includes some interlocked operations that you can use to perform simple operations on a shared memory location or a variable.

.NET Framework provides several classes to manage the locking of shared resources. These classes include Monitor, WaitHandle, Mutex, Semaphore, and ReaderWriterLock.

The Monitor class is a static class used by a thread to acquire an exclusive lock on an object so that other threads are not able to use that object while it is being monitored. The use of the Monitor class is similar to that of the SyncLock or lock blocks in Visual Basic and C# respectively. To start synchronization, the thread must call the Enter method of the Monitor class and pass the object to be locked as a parameter. To end synchronization, the thread must call the Exit method and pass the same parameter. The code is synchronized between the calls. Although the functionality of the Monitor class is exactly the same as that of the SyncLock and lock blocks, this class provides better control of the synchronization code through a set of methods.

The Mutex class derives from the WaitHandle class and provides the same functionality achieved through the Monitor class, but it can synchronize threads in different application domains. There are two types of mutexes that can be created, local and system mutexes. A local mutex can only be used within the process where it was created, while a system (or named) mutex can be used by any process in the operating system. Once a mutex is created, it can only be released from the thread in which it was created.

You can use the Semaphore class to synchronize access to resources by a pool of threads, instead of a single thread at once. When using the Semaphore class, you can specify the maximum number of threads that can access the resources simultaneously. Other threads must wait in queue until the executing threads release the semaphore. You can achieve this functionality by maintaining a count of new threads that can access the resource, decrementing this count every time a thread enters the semaphore, and incrementing it every time a thread leaves the semaphore. Whenever the counter is greater than zero, new threads can enter the semaphore. Once the counter is zero, incoming threads will be queued until the counter increases. Just like Mutex, Semaphore can be local or global (named).
You can use the Semaphore class when you want to restrict the number of threads executing a piece of code.

You can use the ReaderWriterLock class to synchronize access to resources by using a pool of threads with read access or a single thread with write access. You can use different methods in the ReaderWriterLock class to lock resources for either read or write access. When a thread submits a read lock request, the ReaderWriterLock class works similar to the Semaphore class, allowing access to resources by multiple threads. Once a writer lock is requested, all new reader requests are queued. After the existing locks are released, the writer lock is honored. A lock can be represented by a variable of type LockCookie for multiple requests, such as when upgrading a reader lock to a writer lock and vice versa. However, a thread cannot have both reader and writer locks at the same time; it must change the lock type by using predefined methods.
You can use the ReaderWriterLock class in situations where changes to resources are infrequent and multiple threads are able to share the resource.

When working with the Monitor class, you can implement signaling by using the Pulse method. However, you can also use other classes such as Mutex, Semaphore, EventWaitHandle, and RegisteredWaitHandle for signaling.

Signaling may be necessary when the same object is being used to execute different actions by different threads, and the synchronization of these different threads is needed. For instance, consider a bank account object being used simultaneously to both withdraw and deposit money in an account. The deposit method reads the balance, followed by the withdraw method. The withdraw method then changes the balance based on the amount withdrawn. Since the deposit method had already read the balance, it adds the amount to be deposited to the old balance, and therefore, saves the new balance incorrectly. This error could be prevented if the two threads were using signaling.

All classes that derive from the WaitHandle class can use signaling, such as the Mutex, Semaphore, and EventWaitHandle classes.

You can use the EventWaitHandle class to exchange signals among different threads and processes. EventWaitHandle can be local (to the process) or global (named). The EventWaitHandle class has two child classes, AutoResetEvent and ManualResetEvent. These two classes are very similar; you can use both to signal to a thread whether it can execute or not after waiting for a signal.
You can think of the signal as a green (go) or red (stop) light letting the thread know whether to wait or move on. Once a thread makes a call to wait on a signal, it stops until a green light is received. The signal remains green until a thread turns it red again. This describes the Set (turn green) and Reset (turn red) methods available in the ManualResetEvent class. The AutoResetEvent class works in a similar way; however, the light turns red automatically after turning green and letting one, and only one, thread continue.

You can use the AutoResetEvent class in the same way as the EventWaitHandle class when working with an object in the AutoReset mode. The only difference is that the event created is a local event, with thread affinity. You can use this class when the signal does not need to cross application domains and the AutoResetEvent class automatically resets itself between signaled and non-signaled states. The only constructor for this class takes a parameter of type Boolean indicating if the initial state of the event is signaled.

You can use the ManualResetEvent class in the same way as the EventWaitHandle class when working with an object in the ManualReset mode. The only difference is that the event created is a local event, with thread affinity. You should use this class when the signal does not need to cross application domains. The ManualResetEvent class remains signaled until you manually switch it to a non-signaled state and vice versa.
The only constructor for the ManualResetEvent class takes a parameter of type Boolean indicating if the initial state of the event is signaled. You can use the OpenExisting method of the ManualResetEvent class to open a named event that already exists.

When attempting to access a shared resource by using a thread from a thread pool, your application may have to wait in queue until the resource is free. Your application can reserve a place in queue in a method analogous to you taking a numeric ticket to stand in queue while at a public office. The ThreadPool class includes a method named RegisterWaitForSingleObject that returns a WaitHandle class. WaitHandle represents your application’s reserved spot in the queue and your object is signaled when the resource in question is free.
The RegisteredWaitHandle class represents the WaitHandle returned by the RegisterWaitForSingeObject method. If you decide that you would like your application to surrender its place in line and no longer wait for a resource, you may call the Unregister method.

The Interlocked class is a static (Shared) class that you can use to synchronize shared thread access to a variable. Variables that are interlocked have an exclusive lock placed on them so that no other threads can interrupt operations. The operations that can be performed on an interlocked variable are limited to very simple operations such as simple mathematic calculations. One benefit of using the Interlocked class is that it performs operations at a very low level, directly with the operating system and is, therefore, very fast.

In asynchronous programming, calls to various methods are made in a parallel manner where a method call does not wait for the other method to complete before application execution continues.

Sunday, April 27, 2008

Implementing service processes, threading, and application domains in a .NET Framework application (11 %)

Implement, install, and control a service. (Refer System.ServiceProcess namespace)
•Inherit from ServiceBase class
•ServiceController class and ServiceControllerPermission class
•ServiceInstaller and ServiceProcessInstaller class
•SessionChangeDescription structure and SessionChangeReason enumeration

F.Delegates

Delegates
  • Reference types
  • Type safe , instances of objects with their own properties and methods.
  • Declare a delegate type,define a variable of a delegate type,create an instance of a delegate.
  • Used to indirectly call one or more methods at run time,pass a delegate by ref as a parameter of a method
  • Method is not specified when declaring the delegate type or a variable based on the delegate type
  • Invoking Method is specified when an instance of delegate is created and dynamically associate one or more instances with the variable at runtime.

Uses:

  • In creation of events. e.g. all events in 2.0 based on delegate types
  • creation of asynchronous method calls.e.g. callbacks in 2.0 based on delegate types
  • If you have two objects that have similar methods with identical method signatures, you can use the same delegate to invoke them even if two objects are not related,methods have different names.
  • You can use generics in delegate signatures. By using generics, you can instantiate a strongly typed delegate that can be used at run time with full type safety without specifying a particular type in the signature of your delegate type declaration.This helps you create an event in a generic class and specify the return type and parameter types when you create an instance of the delegate.
  • Invoke static or instance methods
  • In C#,you can have anonymous methods

Types:

  • A singlecast delegate references only a single method.
  • A multicast delegate references many methods . All delegates are implicitly multicast delegates. By adding multiple method references to a delegate’s invocation list, you can invoke all the methods with one call to the delegate.This process is referred to as multicasting. You can invoke each method in the invocation list individually. This is useful if you want to determine the return value or output parameters of each method call or if you do not want to call certain methods in certain circumstances.

C# exeception rules to delegate

Covariance : occurs when the return type of the method referenced by the delegate inherits from the return type of the delegate itself. Because the method’s return type inherits from the delegate’s return type, the signatures are still considered a match.

Contravariance :Contravariance permits the declaration of a delegate with parameters that inherit from the types used in the parameters of the method that will be invoked. However, for contravariance to work, the order and number of parameters in the signatures of the delegate as well as the method must still match.

Saturday, April 26, 2008

D. Specialized collection

System.Collections.Specialized
Specialized collections:Predefined collections that serve a special or highly specific purpose

Specialized String Collection :
StringCollection class: same behavior as the generic List class when elements are specified as string.
Strongly typed version of ArrayList
Accepts Null reference as a valid value.
Allow duplicate Element
Zero based index
String comparision is case sensitive

StringDictionary class: exact same behavior as the generic Dictionary class, when the key is specified as a string and the value is specified as a string.
Can accept a null value but the key cannot be a null reference
Case insensitive

StringEnumerator class provides enumeration for the string collection.
CollectionsUtil class allows to create a case insensitive Hashtable or a case insensitive SortedList.
Hashtable name=CollectionsUtil.CreateCaseInsensitiveHashtable();

Specialized Dictionary collection:
HybridDictionary class internally switches to either a ListDictionary or a Hashtable to store data, depending on the number of elements.
ListDictionary provides a better performance for less than 10 elements
Not suitable in conditions when performance is important.

Hashtable provides a better performance for more than 10 elements.
OrderedDictionary can store elements sorted by key and sorted by index. This class is very efficient if the number of elements is 10 or less than 10.

Specialized Named Collection:
The named collection classes provide the abstract base class for a collection of associated string keys and object values that you can access either by the key or by the index.
It allows multiple string values to be associated with a single string key.
It provides a class that you can derive from to create your own key/value collections, with their own specialized behavior
Default initial capacity for a NameValueCollection is zero.
Dynamically resizes.
In NameValueCollection, a null reference is allowed for either a key or a value.

Specialized Bit collection:
A BitVector32 provides a simple structure that stores Boolean values and small integers.
It stores Boolean values in a 32-bit structure hence more efficient than bit structure.

A BitVector32.Section is a window into the BitVector32 and is composed of the smallest number of consecutive bits that can contain the maximum value specified in CreateSection. For example, a section with a maximum value of 1 is composed of only one bit, whereas a section with a maximum value of 5 is composed of three bits
The BitVector32.Section allows you to store small integers within a BitVector32 class.

Generic Collection

List : Equivalent to Arraylist of NonGeneric collection
Unlike Arraylist, can store value type as well
You need to specify datatype.
Uses List.Enumertor for iteration.
e.g. Listnames = new List ();
dim names as List = new List(of String)

Generic Stack : Equivalent to Non generic Stack but you specify a datatype
Use Push to add
Use Pop to remove element

Generic Queue:
Enqueue to add element
Dequeue to remove element

LinkedList : Createss and manage a strongly typed doubly linked list.
Every node contains reference to the previous and next nodes in the list.

Collection and Collection Interfaces

INTERFACES
IComparable : Used to compare two objects and determine which object is greater.
The CompareTo method returns 1, 0, or -1 if the value of the current object is greater than, equal to, or less than the object passed as a parameter to this method.

ICollection: defines the size, enumerators, and synchronization methods for all non-generic and generic collections.
Non-Generic : AddAt, AddItem, GetEnumerator, Item methods,IsReadOnly and Count properties
Generic : Add, Clear, Contains, CopyTo, Remove,Count methods.

IList :Used to index a collection..
Generic & Non-Generic : Insert, IndexOf, and RemoveAt methods.
Non-Generic: Add, Clear, Contains, IndexOf, Insert, Remove, and RemoveAt methods.

IComparer: The non-generic IComparer interface provides the Compare method same as Compare method of IComparable.
In the generic version ,both parameters are passed as a specific data type.

IEqualityComparer:Used to check if two collections are equivalent.
Non-Generic: Equals(determines if two system.Object are equivalent or not) and GetHashCode(returns same hashcode if two collections are equivalent.
The generic version accepts parameters of a specific data type.

IDictionary:The non-generic IDictionary provides the collection key/value pair behavior.
The generic version allows the key and the value to be declared as specific data type.

IEnumerable: It provides the GetEnumerator method to enumerate the collection and returns the IEnumerator data type.

IEnumerator: Non genric version supports a simple iteration in a non-generic collection. This interface is the base interface of all non-generic enumerators. e.g.For each in vb.net and foreach in C#
Non-Generic: MoveNext , Reset methods ,current property(returns a data type of system.object)
The generic version provides the strongly typed Current property.

ArrayList : Can be resized.
Implements IList

Stack : based on LIFO

Queue :Based on FIFO

Iterator : used in C#

Comparer :
Default method that provides a comparison based on the current culture
DefaultInvariant that provides a culture-independent comparison

HashTable : represents a collection of name/value pairs
The key is stored as an object and its hash code is used to identify the value which makes data retrieval very fast.
Allows you to dynamically add and remove elements without re-indexing.
Doesnt have a generic version
Implements IEnumerator
Disadvantage : doesnt allow sorting

SortedList:represents a collection of name/value pairs that are accessible either by key or by index, but are sorted only by keys.
The SortedList class maintains two arrays to store the elements of the list, one array for the keys and another for the associated values.
The elements are sorted by keys.
Does not allow duplication of keys.
Indexing adjusts when you add or remove a element .
Slower than hashtable becoz of sorting process. However,compared to hashtable more flexible as flexibility it can be accessed by key or index.

BitArray: implements a bit structure, which represents a collection of binary bits, 1s and 0s.
The size of a bit structure in memory depends on the number of elements in the collection.
Elements are accessed using an integer index.
Zero-based indexes.
To add element use Length property

Wednesday, April 23, 2008

My Notes on A

When to use structure :



  • If the type will perform better as a value type rather than reference, use a structure instead of class.
  • Instance size less than 16bytes
  • Represents a single value
  • Will not be changed after creation
  • Will not be cast to a Reference type

Advantages of using Generics:

  • Processing is fast as boxing and unboxing are not required
  • Catch errors at compile time by ensuring typesafety
  • You can use constraints on the types: Interface,Base Class,Constructor,Reference or ValueType

IConvertible: Converts an object to CLR datatypes

ICloneable: defines the Clone method that you can implement to do a deep cloning of an object and it's references to other objects

IFormattable: defines the ToString method that you can implement to format the value of the current instance by using the specified format.

IDisposable: defines the dispose method that you can implement to release the resources with the help of a supporting custom-defined ReleaseResource method and remove the current object from the finalization queue. This relieves the garbage collector from calling the finalizer of an object after the object is disposed

New in 2.0

  • Nullable
  • Operator
  • Generic types .eg.EventHandler
IEquatable: applicable to Generic class used Equal method
TypeForwarding
  • Conversion operator ( Vb.Net:Widening,Narrowing C#:implicit,explicit)

1. Developing applications that use system types and collections (15 percent)

A .Manage data in a .NET Framework application by using the .NET Framework 2.0 system types. (Refer System namespace)

Value types ( VB.Net )
Nullable type (VB.Net)
Reference types
Attributes
Generic types (VB.Net)
Exception classes (VB.Net)
Boxing and UnBoxing (VB.Net)
TypeForwardedToAttribute Class

B.Manage a group of associated data in a .NET Framework application by using collections. (Refer System.Collections namespace)
•ArrayList class
Collection interfaces
ICollection interface and IList interface
IComparer interface and IEqualityComparer interface
IDictionary interface and IDictionaryEnumerator interface
IEnumerable interface and IEnumerator interface
Iterators
Hashtable class
CollectionBase class and ReadOnlyCollectionBase class
DictionaryBase class and DictionaryEntry class
Comparer class
Queue class
SortedList class
BitArray class
Stack class

C.Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace)
•Collection.Generic interfaces
Generic IComparable interface (Refer System Namespace)
Generic ICollection interface and Generic IList interface
Generic IComparer interface and Generic IEqualityComparer interface
Generic IDictionary interface
Generic IEnumerable interface and Generic IEnumerator interface
IHashCodeProvider interface (obsolete now)

Generic Dictionary
Generic Dictionary class and Generic Dictionary.Enumerator structure
Generic Dictionary.KeyCollection class and Dictionary.KeyCollection.Enumerator structure
GenericDictionary.ValueCollectionclass and Dictionary.ValueCollection.Enumerator structure

Generic Comparer class and Generic EqualityComparer class
Generic KeyValuePair structure
Generic List class, Generic List.Enumerator structure, and Generic SortedList class
Generic Queue class and Generic Queue.Enumerator structure
Generic SortedDictionary class
Generic LinkedList
•Generic LinkedList class
Generic LinkedList.Enumerator structure
Generic LinkedListNode class

Generic Stack class and Generic Stack.Enumerator structure

D.Manage data in a .NET Framework application by using specialized collections. (Refer System.Collections.Specialized namespace)
•Specialized String classes
StringCollection class
StringDictionary class
StringEnumerator class


•Specialized Dictionary
HybridDictionary class
IOrderedDictionary interface and OrderedDictionary class
ListDictionary class


•Named collections
NameObjectCollectionBase class
NameObjectCollectionBase.KeysCollection class
NameValueCollection class


•CollectionsUtil
BitVector32 structure and BitVector32.Section structure

E.Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace)
IComparable interface
IDisposable interface
IConvertible interface
ICloneable interface
IEquatable interface
IFormattable interface

F.Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace)
Delegate class
EventArgs class
EventHandler delegates

Sunday, April 20, 2008

Preparation Guide for 70-536

Microsoft recommends MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 - Application Development Foundation and MSDN Library for preparation. After finishing a topic from the book, you should go through the MSDN library to enhance your understanding of that topic. I could find the complete list of objectives from Microsoft's site but I have to hunt for the corresponding link to the MSDN library. In the coming posts, I would list the objectives covered in a topic, the corresponding MSDN link and also the percentage which that topic carries.

Saturday, April 19, 2008

70-536 (Microsoft .NET Framework 2.0—Application Development Foundation) Preparation

After working for last 2-3 years in .Net, I have finally decided to take 70-536 exam. I am planning to take it in next couple of days. Whatever topic I go through I will try to summarise that here so that it could help someone else as well.

Get\Set Property at runtime

One of my recent tasks has required me to set value of a property at runtime.

VB.Net
Imports System.Reflection

Public Readonly property MyObject as Object
'Use the MyAssembly property created in previous post but make sure you are not using ReflectionOnlyLoad method
Get Dim assy as assembly = MyAssembly
Dim obj as Object = assy.CreateInstance("MyClassName")
return obj
End Get
End Property

Public ReadOnly Property MyPropertyInfo(ByVal propName as String,obj as Object) as PropertyInfo
Get Dim pinfo as PropertyInfo = Nothing
If not obj is Nothing Then
Dim types() as Type = Type.EmptyTypes
pinfo = obj.GetType.GetProperty(propName,types)
End If
return pinfo
End Get

Public property MyProperty as Object
Get
Dim obj as Object = MyObject
Dim value as Object = Nothing
'Get the property of the Object
Dim pinfo as PropertyInfo = MyPropertyInfo("MyPropertyName",obj)
'Do we have a object and the information about the property?
If Not obj Is Nothing AndAlso Not pinfo Is Nothing Then
'Get the value of property
value = pinfo.GetValue(obj,Nothing)
End If
Return value
End Get
Set(ByVal value as Object)
Dim obj as Object = MyObject
Dim pinfo as PropertyInfo = MyPropertyInfo("MyPropertyName",obj)
If Not obj is Nothing AndAlso Not pinfo is Nothing Then
'Get the type of the property
Dim proptype as Type = pinfo.Type
'Is the value a string?
If TypeOf Value is String then
'Depending on the property type cast the value to appropriate Type
Select Case true
Case TypeOf proptype is Boolean
value = Convert.ToBoolean(value)
Case TypeOf proptype is Date
value = Convert.ToDateTime(value)
Case TypeOf proptype is Integer
value = Convert.ToInt32(value)
Case TypeOf proptype is Single
value = Convert.ToSingle(value)
Case TypeOf proptype is Double
value = Convert.ToDouble(value)
Case proptype.IsEnum
value = Enum.Parse(proptype,Value.ToString())
End Select
pinfo.SetValue(obj,Value,Nothing)
End Set
End Property


That was a generic way of getting/setting any property of any class at the runtime. I have used "MyClassName" and "MyPropertyName" for creating an instance of object and getting the property information but that could be replaced by whatever class and whichever property of that class you want to retrieve. If you don't pass empty types while retrieving property info it might give you ambiguous match found exception. If you have 2 properties in your class, one without any parameter and the other one with a parameter, at runtime in absence of Emptytypes it would get confused which property you want to retrieve if you want to access property without the parameter.

Tuesday, April 15, 2008

Loading Assembly at runtime

Reflection is a wonderful feature to get any information about a class at the runtime. Following are the different ways of loading an assembly which I would like to share with everyone.

VB.Net
Imports System.Reflection.Assembly

Public ReadOnly property MyAssembly as Assembly
Get
dim assy as assembly = nothing

dim assypath as string = "C:\yourfilepath.dll"

dim assyfullname as string = "MyAssemblyName,Version = 1.0.0.0" + _
"Culture = neutral,PublicKeyToken = ba0014rg1234809"

dim assypartialname as string = "MyAssemblyPartialName"

'If you know the path from where to load the assembly
assy = LoadFile(assypath)
'If you want to load the executing assembly
assy = GetExecutingAssembly()
'If you want to load the assembly that started the process
assy = GetEntryAssembly()
'If you want to load the assembly from one level up in the stack
assy = GetCallingAssembly()
'If you want to load the assembly from GAC,however in .Net 2.0 this method has become obsolete but you can still use it.
assy = LoadWithPartialName(assypartialname)
'If you want to load the assembly only for interoggation but not for creating instance
assy = ReflectionOnlyLoad(assyfullname)
Or
assy = ReflectionOnlyLoadFrom(assypath)
return assy
End Get

I have mainly used LoadWithPartialName,GetExecutingAssembly
 
Google