lock Statement (C# Reference)

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form:

Object thisLock = new Object();
lock (thisLock)
{
// Critical code section.
}


The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The section Threading (C# and Visual Basic) discusses threading.

The lock keyword calls Enter at the start of the block and Exit at the end of the block.

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

lock (this) is a problem if the instance can be accessed publicly.

lock (typeof (MyType)) is a problem if MyType is publicly accessible.

lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

    
using System.Threading;

    class ThreadTest
    {
        public void RunMe()
        {
            Console.WriteLine("RunMe called");
        }

        static void Main()
        {
            ThreadTest b = new ThreadTest();
            Thread t = new Thread(b.RunMe);
            t.Start();
        }
    }
    // Output: RunMe called





The following sample uses threads and lock. As long as the lock statement is present, the statement block is a critical section and balance will never become a negative number.



    using System.Threading;

    class Account
    {
        private Object thisLock = new Object();
        int balance;

        Random r = new Random();

        public Account(int initial)
        {
            balance = initial;
        }

        int Withdraw(int amount)
        {

            // This condition will never be true unless the lock statement
            // is commented out:
            if (balance < 0)
            {
                throw new Exception("Negative Balance");
            }

            // Comment out the next line to see the effect of leaving out 
            // the lock keyword:
            lock (thisLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }

        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }

    class Test
    {
        static void Main()
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
        }
    }


Virtual Methods

Declaring a class member as *virtual* allows inheriting classes to override the base class behavior.
This is one of the pillars of OOP known as polymorphism.

Declaring a method as *sealed* breaks this inheritance chain., preventing inheriting classes from overriding base class methods.


class BaseClass
{
public virtual void Method_01()
{
Console.WriteLine("BaseClass.Method_01");
}
public virtual void Method_02()
{
Console.WriteLine("BaseClass.Method_02");
}
}
class DerivedClass : BaseClass
{
public override void Method_01()
{
Console.WriteLine("DerivedClass.Method_01");
}
public override sealed void Method_02()
{
Console.WriteLine("DerivedClass.Method_02");
}
}
class Consumer : DerivedClass
{
public override void Method_01()
{
Console.WriteLine("Consumer.Method_01");
}
public new void Method_02()
{
Console.WriteLine("Consumer.Method_02");
}
}



static void Main(string[] args)
{
BaseClass bc;
bc = new DerivedClass();
bc.Method_01();
bc.Method_02();
Console.ReadLine();
bc = new Consumer();
bc.Method_01();
bc.Method_02();
Console.ReadLine();
}

Customize default folder of Windows Explorer

If you have noticed when you click on the Windows Explorer icon default folder in task bar in Win 7, it would go to libraries folder. You can customize this behavior. Let’s say we need to set the default behavior to open My Computer.



Here are steps to change it from libraries to my computer:


1. Close all the windows explorer windows.

2. Press Shift key and right click on the explorer icon



3. Click Properties menu item and Click Properties menu item and Go to Shortcut tab.

4. Change the Target to : %SystemRoot%\explorer.exe /E,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}







5. Click Apply and Ok button.


So next time you open the windows explorer it would open my computer folder.

Windows 7 Tips

Minimize Everything except the current window

Many times we have a lot of applications open on the screen and if we have to minimize or hide other windows that are open in the background.
Then this tip can be handy.
Press the Windows Key + Home Key.
This would minimize all the background windows.

Box Selection and Multi-Line Editing with VS 2010

Technology:
Visual Studio 2010

Title:
Box Selection and Multi-Line Editing with VS 2010

Description:
Box selection is a feature that has been in Visual Studio for a while. It allows you to select a rectangular region of text within the code editor by holding down the Alt key while selecting the text region with the mouse.

With VS 2008 you could then copy or delete the selected text.

VS 2010 now enables several more capabilities with box selection including:
• Text Insertion: Typing with box selection now allows you to insert new text into every selected line

• Paste/Replace: You can now paste the contents of one box selection into another and have the content flow correctly

• Zero-Length Boxes: You can now make a vertical selection zero characters wide to create a multi-line insert point for new or copied text

These capabilities can be very useful in a variety of scenarios.

Some example scenarios: change access modifiers (private->public), adding comments to multiple lines, setting fields, grouping multiple statements together, restructuring HTML.