Tuesday, February 24, 2009

Expensive Thread creation

 

Creating a thread involves following points :

  • Allocate and initialize a thread kernel object
  • each thread gets 1MB of address space – user stack
  • each thread gets 12KB of address space – kernel stack
  • notify every DLL about the newly created thread
  • notify every DLL when a thread is destroyed
  • free kernel object and the stacks

All this is pretty expensive as against ThreadPool, in ThreadPool, CLR doesn’t create (except for the 1st time) or destroy (except under idle condition) threads

Thread vs. ThreadPool

There are situations when you should not use ThreadPool and instead use Threads -

  1. When you need to change priority of thread.
  2. When you need to create a foreground thread.
  3. When the thread is executing long running task.
  4. When you need to have the ability to abort a thread.

Sunday, February 15, 2009

Guess output


bool a1 = null == 1; //false Warning The result of the expression is always 'false' since a value of type '<null>' is never equal to 'null' of type 'int'
bool a2 = null != 1; //true Warning    The result of the expression is always 'true' since a value of type '<null>' is never equal to 'null' of type 'int'
bool a3 = null > 0; //false Warning Comparing with null of type 'int?' always produces 'false'
bool a4 = null < 0; //false Warning    Comparing with null of type 'int?' always produces 'false'

Exceptions - Part1


Consider the following code :

public static void Main()
{
try
{
Inner();
}
catch (Exception e)
{
Console.WriteLine("Main Catch");
}
finally
{
Console.WriteLine("Main finally");
}
}
private static void Inner()
{
try
{
StillInner();
}
finally
{
Console.WriteLine("Inner finally");
}
}
private static void StillInner()
{
try
{
Console.WriteLine("Throwing from StillInner");
throw new Exception("StillInner");
}
finally
{
Console.WriteLine("StillInner finally");
}
}

The output is as follows :

Throwing from StillInner
StillInner finally
Inner finally
Main Catch
Main finally

As you can see, catch block was searched in the call stack, and all finally’s leading to it were executed before the catch could be executed and finally the catching finally was executed.

What if Main did not have the required catch type? Then the output is as follows :

Throwing from StillInner

Unhandled Exception: System.Exception: StillInner
at ConsoleApplication1.MainClass.StillInner() in …
at ConsoleApplication1.MainClass.Inner() in …
at ConsoleApplication1.MainClass.Main() in …

StillInner finally
Inner finally
Main finally

So, basically, finally will always get executed even if there is no catching block.
The only situation in which finally does not get executed is when the stack overflows.

When stack overflows, nothing is executed and you get the following message :

Process is terminated due to StackOverflowException.

Even if you have the StackOverflowException handler, it is not executed.

There is one more situation, assume, the StillInner Class throws exception in the finally block itself, then? Then it is treated as if the exception was generated outside the finally and a search for the catchtype is initiated, if it is found in Main, then you get the following output :

Throwing exception from StillInner Finally
Main Catch
Main finally
After Main try catch finally


What you see is that it only executed the Main’s finally not the Inner Finally, also after executing finally, main continued execution till it finished.

Wednesday, February 11, 2009

for-each-ing

People mypeople = new People();
foreach (Person indivudual in mypeople)
{
Console.WriteLine(indivudual);
}
To write a foreach loop for your collection class you need to implement IEnumerable and IEnumerator. Here’s a simple way to do it.

class Person
{
private string _Name;

public Person(string name)
{
_Name = name;
}
public override string ToString()
{
return _Name;
}
}
class People:IEnumerable
{
List<Person> people = new List<Person>();

public People()
{
people.Add(new Person("A"));
people.Add(new Person("B"));
people.Add(new Person("C"));
people.Add(new Person("D"));
}

//IEnumerable<Person> Members
public IEnumerator GetEnumerator()
{
return people.GetEnumerator();
}
}
Here instead of creating a enumerator, I am simply using the List class’s enumerator. I believe that is how you will use in most cases.

Now, you will also find IEnumerable<T> and IEnumerator<T>, they have something to do with LINQ, will post more on that later. MSDN says if you implement IEnumerable<T> then you should also implement the non-generic version of IEnumrator.

There is also something else called as iterators - if you need to return only a fragment of your collection. Heres how :

public IEnumerable<Person> ListAll()
{
foreach (Person individual in people)
{
if (individual.ToString() != "B")
yield return individual;
}
}
This can be consumed by the earlier foreach loop and it prints out all individuals except B.

Note that we could also use yield in the GetEnumerator() method.1 question, why 2 interface to do get foreach going? because 1 interface makes sure your class can be enumerated and other interface ensure the enumeration state is maintained. If you have both together then how would 2 different loops (maybe on different threads) maintain different states.

Tuesday, February 10, 2009

Boxing

int i = 1;
object o = i;
o = 10;
Console.WriteLine("{0},{1}", i, o);
//Prints 1,10

So basically, when you box, a copy of your value type is made and stored in the reference type.

Also, Console.WriteLine() does not take int – it takes object, so when an int is passed, it will be boxed before printing. So it is better to use ToString() on value types.

int i = 1;
object o = i;
o = 10;
Console.WriteLine("{0},{1}", i.ToString(), o);
//Prints 1,10

Static Variables

Static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. This heap is separate from the normal garbage collected heap - it's known as a "high frequency heap", and there's one per application domain.

public class A { public static int a = B.b + 1;}
public class B { public static int b = A.a + 1;}
public class MainClass
{
public static void Main()
{
Console.WriteLine("A.a={0}, B.b={1}", A.a, B.b);
// prints A.a=2, B.b=1
}
}

So what happened here is that Console.WriteLine() wanted the value of A.a, to get that it went to the property, now it wanted the value of B.b, this is undefined, so it goes to calculate that value which is A.a+1, so since A.a is by default 0, it uses that value so B.b is given 0+1 = 1 and this 1 is returned as value of B.b to calculate the new value of A.a which now becomes 1+1 = 2.