23 June 2013

Difference between 'Throw' and 'Throw ex'

Today we are going to compare the difference between 'Throw' and 'Throw ex' with an example. I had created a web project and write the following code:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int a = 5, b = 0;

        int c = Divide(a, b);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private int Divide(int a, int b)
{
    return a / b;
}

When I run the applicatin it throws exception like this:

 
'Throw ex' basically re-throw the exception and lost the original stack trace. So it is always difficult to track the original stack trace BUT if I replace 'throw ex' to 'throw' like this:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int a = 5, b = 0;

        int c = Divide(a, b);
    }
    catch (Exception ex)
    {
        throw;
    }
}

private int Divide(int a, int b)
{
    return a / b;
}

Then it will throw exception with original stack trace.

 
 
Key Point: It is better to use 'throw' instead of 'throw ex' where needed BUT observe the above code again. In the above example we are throwing exception in any case and doing nothing inside the catch block THEN why we need try/catch block? In this type of cases it is better to remove try/catch block because we do not need this.

I hope it will clear the difference and also help you to understand invalid usage of try/catch block.

08 June 2013

How volatile keyword work in C#?

Today I was searching for volatile keyword in C#. I have few questions in my mind that how it is really working? how can I test this? so here is what I found useful.

"The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times."

using System;
using System.Threading;
public class Worker
{
  // This method is called when the thread is started. 
  public void DoWork()
  {
    while (!_shouldStop)
    {
      Console.WriteLine("Worker thread: working...");
    }
    Console.WriteLine("Worker thread: terminating gracefully.");
  }
  public void RequestStop()
  {
    _shouldStop = true;
  }
  // Keyword volatile is used as a hint to the compiler that this data 
  // member is accessed by multiple threads. 
  private volatile bool _shouldStop;
}


public class WorkerThreadExample
{
  static void Main()
  {
    // Create the worker thread object. This does not start the thread.
    Worker workerObject = new Worker();
    Thread workerThread = new Thread(workerObject.DoWork);

    // Start the worker thread.
    workerThread.Start();
    Console.WriteLine("Main thread: starting worker thread...");
    // Loop until the worker thread activates. 
    while (!workerThread.IsAlive) ;

    // Put the main thread to sleep for 1 millisecond to 
    // allow the worker thread to do some work.
    Thread.Sleep(1);
    
    // Request that the worker thread stop itself.
    workerObject.RequestStop();


    // Use the Thread.Join method to block the current thread  
    // until the object's thread terminates.
    workerThread.Join();
    Console.WriteLine("Main thread: worker thread has terminated.");
  }
  
  // Sample output: 
  // Main thread: starting worker thread... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: terminating gracefully. 
  // Main thread: worker thread has terminated.
}

Another article contain following about Volatile keyword

The point of volatile is that multiple threads running on multiple CPU's can and will cache data and re-order instructions.

If it is not volatile, and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems.

If it is volatile, this just ensures the 2 CPU's see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid

Reference:http://msdn.microsoft.com/en-us/library/vstudio/x13ttww7.aspx
http://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock