Saturday, August 25, 2007

Pass by value or Pass by reference

Here is a simple example of parameter passing in C#..

   1: public class ParameterPassingSample
   2: {
   3:     public ParameterPassingSample()
   4:     {
   5:     }
   7:     public void  CallingMethod()
   8:     {
   9:         StringBuilder sb1 = new StringBuilder("Test");
  10:         CalledMethod(sb1);
  11:         System.Diagnostics.Debug.Assert("Test test"==sb1.ToString(),"String equal");
  12:     }
  14:     public void CalledMethod(StringBuilder sb2)
  15:     {
  16:         sb2.Append(" test");
  17:     }
  18: }

Since CalledMethod  function changed the sb value, it will easily give you an impression that Parameter is passed by reference. Actually, it's not.

parameter memory layour

Sb2 is a new string builder object, and it points to the same string builder object in memory. So, when CalledMethod change the value, the value which the original string object (sb1) refers also change. This doesn't mean "pass by reference", it is still "pass by value".  Here is another example to show this.

   1: public class ParameterPassingSample
   2: {
   3:     public ParameterPassingSample()
   4:     {
   5:     }
   7:     public void  CallingMethod()
   8:     {
   9:         StringBuilder sb1 = new StringBuilder("Test");
  10:         CalledMethod(sb1);
  11:         System.Diagnostics.Debug.Assert("Test"==sb1.ToString(),"String equal");
  12:     }
  14:     public void CalledMethod(StringBuilder sb2)
  15:     {
  16:         sb2 = null;
  17:     }
  18: }

Here , if sb2 changes to null, it doesn't affect the value of sb1. 

parameter memory layour

The difference between those two examples are "change the value the parameter points to" or "change the value of the parameter itself".

Monday, August 20, 2007

What are the overhead fields when you create an object in CLR

In CLR, each object has two overhead fields: a type object pointer and a sync block index.ObjectsLayOutCLR

Each of the fields requires 32 bits, adding 8 bytes to each object.

WaitHandle hierarchy

Here is a reflector screenshot of the relationships among the different synchronization object. The wait handle is a simple class whose sole purpose is to wrap a windows kernel object.


As you can see, EventWaitHandle, Mutex, and Semaphore are all inheriting from the wait handle object. When a thread is waiting on the kernel object, the thread must always transition from the user mode to the kernel mode, causing the thread to incur a performance hit. So if you want to do the thread synchronization inside an AppDomain, it's best that you simply use the Monitor, which is much more efficient than the kernel object. However, if you have to do the synchronization between different appdomains, processes, you have to use those windows kernel objects.

Saturday, August 18, 2007

Thread from the thread pool or dedicated thread.

Use thread from the thread pool to execute some asynchronous task instead of a dedicated thread can save the resources needed to create that dedicated thread.

A dedicated thread is only needed if the thread needs to run in a special priority, since all the threads from the thread pool are running in the normal priority, and you don't have access to change the priority for the thread in the thread pool.

Another reason is that if the thread needs to be run in foreground, a dedicated thread is also needed since all the threads in the thread pool are running in the background.

If the task is taking extremely long time to finish, then a dedicated thread is also needed because it is a little bit challenging for the thread pool to figure out whether to create additional thread when that task is running.

Friday, August 17, 2007

Why do you want to explicit declare an event.

In C#, you can simply declare an event by using this line :

public event EventHandler<EventArgs> MyImplicitEvent;
It's simple. But under the hood, the compiler did a lot of things for you. The line above will be translated into the

   1: // 1. A PRIVATE delegate field that is initialized to nullprivate 
   2: EventHandler<EventArgs> MyImplicitEvent = null;
   3: // 2. A PUBLIC add_Xxx method (where xxx is the Event name)
   4: // Allows objects to register interest in the event.
   5: [MethodImpl(MethodImplOptions.Synchronized)]
   6: public void add_MyImplicitEvent(EventHandler<EventArgs> value) 
   7: {
   8:     MyImplicitEvent = (EventHandler<EventArgs>)
   9:     Delegate.Combine(MyImplicitEvent, value);
  10: }
  11: // 3. A PUBLIC remove_Xxx method (where Xxx is the Event name)
  12: // Allows objects to unregister interest in the event.
  13: [MethodImpl(MethodImplOptions.Synchronized)]
  14: public void remove_MyImplicitEvent(EventHandler<EventArgs> value) 
  15: {
  16:     MyImplicitEvent = (EventHandler<EventArgs>)Delegate.Remove(MyImplicitEvent, value);
  17: }

So, the compiler will inject the MethodImplOptions.Synchronized attribute into the add_ and remove_ method. By default, those methods implement the synchronization using the object itself as the the thread-synchronization lock. However, this object is public, and you shouldn't use this object to do the synchronization. Because the malicious code could use this public object to deadlock threads that use this instance of object.

A better way to handle this to do the parts which compiler generated for you by yourself. like this.

   1: // Private instance field created to serve as thread synchronization lock       
   2:  private readonly object m_eventLock = new Object();        
   3:  // Add private field that refers to the head of the delegate list       
   4:  private EventHandler<EventArgs> _myImplicitEvent;       
   5:  // Add an event member to the class        
   6:  public event EventHandler<EventArgs> ImplicitEvent        
   7:  {            // Explicitly implement the 'add' method            
   8:      add            
   9:      {                
  10:          // Take the private lock and add a handler                
  11:          // (passed as 'value') to the delegate list                
  12:          lock (m_eventLock) { _myImplicitEvent += value; }            
  13:      }            
  14:      // Explicitly implement the 'remove' method            
  15:      remove           
  16:      {                
  17:          // Take the private lock and remove a handler                
  18:          // (passed as 'value') from the delegate list               
  19:          lock (m_eventLock) { _myImplicitEvent -= value; }            
  20:      }        
  21:  }

This way, you use the private object m_event Lock to do the synchronization, and you can avoid the problem (code outside of the class will have access to the synchronization object) compiler generated codes have.

Sunday, August 12, 2007


I used the Paint.Net to edit a couple of images today when I tried to edit the html template for my blog. I want to widen the content area, and have to edit a couple of gif files.

I have downloaded the before, but really didn't try it too much. It took me some time to get used to all those concepts if you haven't used any image editing software, but I have to admit it's a really powerful image editing tools if you cannot afford the expensive adobe Photoshop.

Check it here.

Changed the default blog template.

One thing I don't like the blogger is the limited selection of template. I am happy with the one I selected right now, but it gave too much margin to the sidebar, and leave main content area very thin. While it's fine at most times, I did run into a couple of awkward situations when I have to insert some images into the blogger. I have to resize the image to fit into the content area.

I start to play with the html templates codes, and a couple of places I have to edit are :


#outer-wrapper {
  width: 947px; (change from 847 px to 947 px)
  margin: 0px auto 0;
  text-align: left;
  font: $bodyfont;
  background: url( repeat-y; I also have to edit the original tile.gif to make it wider.

#content-wrapper {
  margin-left: 42px; /* to avoid the border image */
  width: 863px; (change from 763px to 863px)

#main {
  float: left;
  width: 560px; (change from 460px to 560px)
  margin: 20px 0 0 0;
  padding: 0 0 0 1em;
  line-height: 1.5em;
  word-wrap: break-word; /* fix for long text breaking sidebar float in IE */
  overflow: hidden;     /* fix for long non-text content breaking IE sidebar float */


#header-wrapper {
   width: 947px; (Add this line)
  margin: 0;
  padding: 0;
  font: $pagetitlefont;
  background: #e0e0e0 url( This image is also needed to be widened.
    no-repeat 0px 0px;

#header {
  width: 863px; (Add this line)
  margin: 0;
  padding: 25px 60px 35px 60px;
  color: $pagetitlecolor;
  background: url( no-repeat bottom left;

It looks pretty easy, but it takes me a couple of hours to figure out all those tricks.