Tuesday, July 24, 2012

Lock Statement in C#

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.
}
For more information, see Thread Synchronization (C# Programming Guide).(MSDN link)
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# Programming Guide)(MSDN LINK) 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)), andlock ("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.)
The following sample shows a simple use of threads without locking in C#.
//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();
}
}
}

Fixed Statement in c#

The fixed statement prevents the garbage collector from relocating a movable variable. The fixed statement is only permitted in an unsafe context. Fixed can also be used to create fixed size buffers.

The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of the statement. Without fixed, pointers to movable managed variables would be of little use since garbage collection could relocate the variables unpredictably. The C# compiler only lets you assign a pointer to a managed variable in a fixed statement.

unsafe static void TestMethod()
{

// assume class Point { public int x, y; }
// pt is a managed variable, subject to garbage collection.
Point pt = new Point();

// Using fixed allows the address of pt members to be
// taken, and "pins" pt so it isn't relocated.

fixed (int* p = &pt.x)
{
*p = 1;
}

}


You can initialize a pointer with the address of an array or a string:

unsafe void Test2()
{
Point point = new Point();
double[] arr = { 0, 1.5, 2.3, 3.4, 4.0, 5.9 };
string str = "Hello World";

fixed (double* p = arr) { /*...*/ } // equivalent to p = &arr[0]
fixed (char* p = str) { /*...*/ } // equivalent to p = &str[0]

fixed (int* p1 = &point.x)
{
fixed (double* p2 = &arr[5])
{
// Do something with p1 and p2.
}
}

}


You can initialize multiple pointers, as long as they are all of the same type:











fixed (byte* ps = srcarray, pd = dstarray) {...}
fixed (int* p1 = &point.x)
{
fixed (double* p2 = &arr[5])
{
// Do something with p1 and p2.
}
}
After the code in the statement is executed, any pinned variables are unpinned and subject to garbage collection. Therefore, do not point to those variables outside the fixed statement.

In unsafe mode, you can allocate memory on the stack, where it is not subject to garbage collection and therefore does not need to be pinned. For more information, see stackalloc.(MSDN LINK)

class Point
{
public int x, y;
}

class FixedTest2
{
// Unsafe method: takes a pointer to an int.
unsafe static void SquarePtrParam (int* p)
{
*p *= *p;
}

unsafe static void Main()
{
Point pt = new Point();
pt.x = 5;
pt.y = 6;
// Pin pt in place:
fixed (int* p = &pt.x)
{
SquarePtrParam (p);
}
// pt now unpinned
Console.WriteLine ("{0} {1}", pt.x, pt.y);
}
}
/*
Output:
25 6
*/

Source :MSDN

Throw statement in c#

Usually the throw statement is used with try-catch or try-finally statements.
You can also rethrow a caught exception using the throw statement

public class ThrowTest2
{

static int GetNumber(int index)
{
int[] nums = { 300, 600, 900 };
if (index > nums.Length)
{
throw new IndexOutOfRangeException();
}
return nums[index];

}
static void Main()
{
int result = GetNumber(3);

}
}
/*
Output:
The System.IndexOutOfRangeException exception occurs.
*/

Sunday, July 22, 2012

Pointers in C# [ -> Operator Reference ]

The -> operator combines pointer dereferencing and member access.

An expression of the form,
x->y
(where x is a pointer of type T* and y is a member of T) is equivalent to,
(*x).y

The -> operator can be used only in code that is marked as unsafe(msdn link).
The -> operator cannot be overloaded.


// compile with: /unsafe
//To compile unsafe code, you must specify the /unsafe compiler option. 
//Unsafe code is not verifiable by the common language runtime. 
struct Point
{
public int x, y;
}

class MainClass12
{
unsafe static void Main()
{
Point pt = new Point();
Point* pp = &pt;
pp->x = 123;
pp->y = 456;
Console.WriteLine("{0} {1}", pt.x, pt.y);
}
}
/*
Output:
123 456
*/



More references about unsafe and c# helpful keywords are below... (source :msdn)

^= Operator Reference C#

The exclusive-OR assignment operator.

An expression of the form
x ^= y
is evaluated as
x = x ^ y 
 
except that x is only evaluated once. The ^ operator performs a bitwise exclusive-OR operation on integral operands and logical exclusive-OR on bool operands.
The ^= operator cannot be overloaded directly, but user-defined types can overload the ^ operator (see operator).

class XORAssignment
{
static void Main()
{
int a = 0x0c;
a ^= 0x06;
Console.WriteLine("0x{0:x8}", a);
bool b = true;
b ^= false;
Console.WriteLine(b);
}
}
/*
Output:
0x0000000a
True
*/
 
 
source:msdn 
 

C# ?: Operator Reference

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;
 
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
 
The conditional operator is right-associative. The expression a ? b : c ? d : e is evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.
The conditional operator cannot be overloaded.

class ConditionalOp
{
static double sinc(double x)
{
return x != 0.0 ? Math.Sin(x) / x : 1.0;
}

static void Main()
{
Console.WriteLine(sinc(0.2));
Console.WriteLine(sinc(0.1));
Console.WriteLine(sinc(0.0));
}
}
/*
Output:
0.993346653975306
0.998334166468282
1
*/
 
source :msdn 

 

 

C# ?? Operator Reference

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}

static string GetStringValue()
{
return null;
}

static void Main()
{
// ?? operator example.
int? x = null;

// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;

// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);

string s = GetStringValue();
// ?? also works with reference types.
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine(s ?? "Unspecified");
}
}
 
source :msdn