Search This Blog

Showing posts with label VB.Net Programming. Show all posts
Showing posts with label VB.Net Programming. Show all posts

Saturday, March 29, 2014

Introduction to Yield Statement in VB.Net

The Yield Statement in VB.Net

The Yield statement returns one element of a collection at a time. The Yield statement is included in an iterator function or Get accessor, which perform custom iterations over a collection.
You consume an iterator function by using a For Each...Next Statement (Visual Basic) or a LINQ query. Each iteration of the For Each loop calls the iterator function. When aYield statement is reached in the iterator function, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
An implicit conversion must exist from the type of expression in the Yield statement to the return type of the iterator.
You can use an Exit Function or Return statement to end the iteration.
"Yield" is not a reserved word and has special meaning only when it is used in an Iterator function or Get accessor.

Iterator Functions and Get Accessors

The declaration of an iterator function or Get accessor must meet the following requirements:
  • It must include an Iterator modifier.
  • The return type must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
  • It cannot have any ByRef parameters.
  • An iterator function can be an anonymous function. For more information
An iterator function cannot occur in an event, instance constructor, static constructor, or static destructor.

Exception Handling in Yield 


A Yield statement can be inside a Try block of a Try...Catch...Finally Statement (Visual Basic). A Try block that has a Yield statement can have Catch blocks, and can have aFinally block.
A Yield statement cannot be inside a Catch block or a Finally block.
If the For Each body (outside of the iterator function) throws an exception, a Catch block in the iterator function is not executed, but a Finally block in the iterator function is executed. A Catch block inside an iterator function catches only exceptions that occur inside the iterator function.

An Example:
Sub Main()
    For Each number In Power(2, 8)
        Console.Write(number & " ")
    Next 
    ' Output: 2 4 8 16 32 64 128 256
    Console.ReadKey()
End Sub 

Private Iterator Function Power(
ByVal base As Integer, ByVal highExponent As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)

    Dim result = 1

    For counter = 1 To highExponent
        result = result * base
        Yield result
    Next 
End Function

Introduction to SyncLock Statement in VB.Net

The SyncLock statement in VB.Net

SyncLock in VB.Net


The SyncLock statement ensures that multiple threads do not execute the statement block at the same time. SyncLock prevents each thread from entering the block until no other thread is executing it.
The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously. If the statements that manipulate the data must go to completion without interruption, put them inside a SyncLock block.
A statement block protected by an exclusive lock is sometimes called a critical section.
  • Branching. You cannot branch into a SyncLock block from outside the block.
  • Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a SyncLock statement.
    You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock object remain unchanged.
  • You can't use the Await operator in a SyncLock block.
How SyncLock Statement works in vb.net

  • Mechanism. When a thread reaches the SyncLock statement, it evaluates the lockobject expression and suspends execution until it acquires an exclusive lock on the object returned by the expression. When another thread reaches the SyncLock statement, it does not acquire a lock until the first thread executes the End SyncLockstatement.
  • Protected Data. If lockobject is a Shared variable, the exclusive lock prevents a thread in any instance of the class from executing the SyncLock block while any other thread is executing it. This protects data that is shared among all the instances.
    If lockobject is an instance variable (not Shared), the lock prevents a thread running in the current instance from executing the SyncLock block at the same time as another thread in the same instance. This protects data maintained by the individual instance.
  • Acquisition and Release. A SyncLock block behaves like a Try...Finally construction in which the Try block acquires an exclusive lock on lockobject and the Finallyblock releases it. Because of this, the SyncLock block guarantees release of the lock, no matter how you exit the block. This is true even in the case of an unhandled exception.
  • Framework Calls. The SyncLock block acquires and releases the exclusive lock by calling the Enter and Exit methods of the Monitor class in the System.Threadingnamespace.
Example

The following example shows a class that maintains a simple list of messages. It holds the messages in an array and the last used element of that array in a variable. The addMessage procedure increments the last element and stores the new message. Those two operations are protected by the SyncLock and End SyncLockstatements, because once the last element has been incremented, the new message must be stored before any other thread can increment the last element again.
If the simpleMessageCollection class shared one list of messages among all its instances, the variables messageCollection and messageseEnd would be declared as Shared. In this case, the variable msgLock should also be Shared, so that there would be a single lock object used by every instance.
Class simpleMessageCollection
    Public messagesCollection() As String = New String(100) {}
    Public messagesEnd As Integer = -1
    Private msgLock As New Object 
    Public Sub addMessage(ByVal newMsg As String)
        SyncLock msgLock
            messagesEnd += 1
            If messagesEnd < messagesCollection.Length Then
                messagesCollection(messagesEnd) = newMsg
            End If 
        End SyncLock 
    End Sub 
End Class