Author Archives: Abhishek Sur

About Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

Workstation GC Vs Background GC

Well, there has been a confusion around the developer community on the differences between the Workstation GC which is by default recommended for standalone machines which targets one single CPU Core and the Background GC which provides multicore execution of Garbage Collections.

In general aspect first let us consider how the Workstation is different from the server.

A Workstation is generally used to provide throughput. There could be a single application running which could use multiple Threads, but the basic idea is to give precedence on the application engine rather than the memory.

On the other hand, Server applications are generally very very long running (for instance ASP.NET Applications) and are job specific, such that when a job needs to be performed, a CPU is assigned to it to perform the task, and once the Task is complete the Thread needs to return back to the Pool. Thus server needs continuous maintenance of its memory usage without hampering the peformance of the application.

Related Read:  LargeObjectHeapCompaction in .NET Garbage Collection

There are three types of GC available currently.

1. Concurrent GC

Concurrent GC maintains a dedicated thread to collect memory footprints. When the GC is performed, all the managed thread may continue to run. For responsive applications, it is recommended to use Concurrent GC as it can still allocate memory while GC is running.

To enable Concurrent GC try :

<gcServer enabled="false"/>

2. Background Workstation GC.

This type of GC is mainly recommended for a client application like Windows Forms or console applications which runs on a single processor. The Workstation GC is a single Thread running on the whole application and collect the whole memory heap at a time concurrently using a single Thread.

To enable workstation gc

<gcServer enabled="false"/>

3. Background Server GC.

This type of GC is ideal for multi-core processor. This kind of GC provides separate managed heap and GC Thread for each processor and can perform more than one GC in parallel. When the GC is performed, all the Threads pointing to the current Core gets suspended. For servers the Background GC is much more recommended.

To enable background GC:

<gcServer enabled=“true"/>

I hope this would help in understanding things better.

Let me know your thoughts.

Inside – String & StringBuilder, which and when ?

Well folks,  even if you think that you know the answer and it is very common, I still think you should read this post to make your concept more clear, because strangely I found there are lot developer who still have some  confusion with the concept even though they read tons of articles in the web about the same topic. This post will give you a bit internal on using String and StringBuilder.

To start with,

Strings are immutable. That means, when you manipulate a string in C#, it creates another string instance in a separate location on heap and points to that location without remembering the previous instance.

Ok, I think you all know this sentence as you might have already came across this and the sentence above is 100% true.
Let’s have a look bit inside

string x = "Daily .NET Tips";
string y = "Daily .NET Tips";

Does it say, x and y will have two different memory locations?

Naah… not at all.

C# does a great job with Strings when dealing with intern. String maintains an intern table which stores all the strings that have been either statically typed as above or used in the program itself. So both x and y variables are initialized with one single address where the string stays.

StringStackHeap Inside   String & StringBuilder, which and when ?

Now let us consider another example :

string x = "Daily .NET Tips";
string y = "Useful Tips and Tricks for .NET Developer";

string z = x + y;

Now here in the above call, x and y are interned into the string intern table but still z creates a memory because strings are immutable and z will point to another separate location which stores the entire content of Z.

String Concat Inside   String & StringBuilder, which and when ?

Here lies the problem. In case you do like:

string z = x + y + " Follow this site at Twitter and Facebook";

The problem became more acute. As strings are immutable, the above line creates a heap allocation for x + y and stores it and then again it creates another memory for storing x + y + “Follow this site at Twitter and Facebook”.

StringConcatOperation thumb1 Inside   String & StringBuilder, which and when ?

Well, this is wastage of memory you can see. Any string operation, like Replace, Remove, Substring etc, will have this problem.

Lets’s have a look at StringBuilder

StringBuilder is a cure for this. StringBuilder stores a character array without using the inner implementation of C# strings and creates a string instance only when the ToString is called for, thus ensuring that StringBuilder becomes mutable.

That means if you write :

StringBuilder z = new StringBuilder();
z.Append(" Follow this site at Twitter and Facebook");

The object z is maintained in heap as a single array instance of characters which keeps on storing the string into it and any replace or removal of some characters inside the StringBuilder will mean the Array gets manipulated not the actual string.

StringBuilderinHeapandStack Inside   String & StringBuilder, which and when ?

I hope this post helped you understanding the exact differences.

Do let me know if you still have confusion in this.

Benefit of Using in Dispose for .NET objects (Why and When ?)

Well, while being in touch with a number of developers, I always find people don’t understand the real meaning of disposing objects. Lets clear our basic understanding on why we need to dispose objects in .NET before understanding the usefulness of Using block.

Why Disposing is necessary ? 

We all know, the code that we run on our managed environment are called managed code. All the objects that we create and automatically picked up by an invisible hand from the program itself called Garbage Collector. The GC is capable of detecting all the objects that do not have reference from the program that is running on, thus sweeping the unnecessary memory from the program and return the memory to the program again.

Now you must be thinking, does it sweep only the objects that are Disposed? Aah.. No, not really.

Difference between Managed and Unmanaged Memory. 

In managed world, memory are created in object Heap (a memory separate from Execution memory but exists in the process) and the program have entire idea on the start and end location of the memory it have been using. But while creating a program, we do not really create only managed memory. Consider you are opening a File from your program. There is a request from your program being made to open a File, and load it to Page File such that your program can access the memory and get data. This memory is totally unmanaged, and your program can only request to clear the memory and Garbage Collection cannot collect it without your request.  In case of File open, the memory is cleared when we call File.Close. Thus there is a gap between the Managed and Unmanaged Memory boundaries. The Garbage Collector can only collect the Memory that .NET has allocated and unmanaged memory will remain if you do not explicitly call to remove it.

For instance, File IO, DataBase Connection Open, Network call, etc all calling an external process running in the kernel of the operating system to allocate / deallocate memory. Therefore in such cases, you need an explicit memory deallocation inside your program. You can also consider a PInvoke as an example here, as you are calling an unmanaged memory yourself.

What are your option to Deallocate Unmanaged Memory?

Well, by this, you already know that managed memory does not require anything from the programmer to deallocate. For unmanaged memory, you can create a method that can deallocate the memory (for instance File.Close which is opened inside a class) and call it whenever GC collects. Well, yes. There is an option to define a destructor inside a class which will be called directly from the GC itself and deallocate memory. Let us look how to write a class with destructor.

public class TestClass
    public TestClass()
        //here you can write File.Open
        //here you can write File.Close

Now if you see the above code you can see, we can create an unmanaged memory inside the constructor, and clear the memory in the Destructor of the class so that the unmanaged memory used by the class gets cleared.

But there is a Catch !!!
As you know your TestClass is a managed memory, the object instance of the TestClass would only be cleared by the Garbage Collector. The destructor is called only by the Garbage Collector itself. Now the problem is, when Garbage Collector collects the unmanaged memory, it generally suspends the Execution Engine (not in case of Background GC introduced recently) while collecting, and it cannot call your destructor while in the middle of the Collection. Hence, it maintains a new list of all objects that needs the Destructor to be called. So when your TestClass is found by the GC, it puts the object reference in the Finalizer Queue, and moves ahead. This will make your object to stay longer as the GC collects the object until it executes again, when it starts by calling destructor of all the queued references and then starts collecting managed objects.

Related Read : Using or Using ?

The usefulness of Disposable pattern in Memory Management

15 01 2014 04 18 35 Benefit of Using in Dispose for .NET objects (Why and When ?)

The Unmanaged memory is expensive. Take an instance of a Database Connection on a Distributed Database system. If your program have to wait for the destructor to call the Close Connection, there would be lot of unused connection remain in the pool for a long time until the GC executes the destructor. .NET solves the problem by giving a simple workaround to write our Dispose method inside the class and a shorthand using block to call the Dispose method automatically. Let us take an example:

public class TestClass : IDisposable
    public TestClass()
        //here you can write File.Open
        //here you can write File.Close
    public void Dispose()
        //Close the file here

Now in the above code what we did is we defined our own method called Dispose which we would call from Managed Code and the GC.SuppressFinalize will ensure that the Destructor will not be called when a Dispose is already called . Thus ensuring the GC to collect the object rather than putting it to the Finalizer Queue.
Related Read : Using Fixed Keyword in C#

Where Using Block lies in ?

Now, as you can remarkably identify that using a IDisposable is way better than having a Destructor in a class, the C# language gives a syntactic sugar to embrace this functionality and encouraging the use of IDisposable rather the destructor. Now let us think how we could have used the class TestClass.

TestClass tclass = new TestClass(); // The line creates an unmanaged memory instance.
// use the tclass to access the unmanaged memory
tclass.Dispose(); //Clear the unmanaged memory.

We also know that unmanaged memory is not pretty safe to access, we must wrap this inside a Try/Catch/Finally block ensuring the try to try creating the object instance, and Finally will ensure that at any cost the memory gets disposed. We will write like this :

TestClass tclass;
     tclass = new TestClass(); // Here memory gets created
     // We use the object tclass here.
   tclass.Dispose(); // here memory gets cleared

The Finally will ensure that even though the try block encounters an exception, the unmanaged memory gets disposed. To give a shortcut to the above code, .NET provides an Using block. To rewrite the above code with Using block, we write like this :

using(TestClass tclass = new TestClass()) // this is here memory is created
 // We use tclass here..
} // this is where dispose called

Thus you can see, the transformation has made the code so much more readable ensuring the programmer never forget to call Dispose from its code. Thus making the life of the programmer simple.

Things to Remember

  1. We only need to dispose objects with Unmanaged Memory.
  2. Destructor loses GC Generation hence it is better to avoid.
  3. GC.SuppressFinalize will allow the programmer to mark an object that destructor does not needed to be called.
  4. Dispose is a better pattern which allows the programmer to clear unmanaged memory.
  5. Using block is a shortcut of try/finally where in the try, it creates an object of the class and in finally the Dispose gets called.

I hope this post will give you better understanding of the Using block and allow you to write better programs in the long run.

Advanced handling of Photo Capture using PhotoCamera in Windows Phone

Well, as I have already dealt with CameraCaptureTask or PhotoChooserTask before for simple scenarios, it is time to go a little further with dealing with continuous capture or even how to switch between FrontFacing Camera or Primary camera etc. To deal with such scenarios, we use the PhotoCamera class and show the stream from camera directly to a canvas or take picture from it. Let us look into the steps to create an app that can make use of Camera Streams directly.

1. First of all, you need to connect to the Cameara. To connect to the Camera, you need to create an object of PhotoCamera and pass the PhotoCamera Source to a canvas element on the App.

private PhotoCamera Camera { get; set; }

var cameraType = CameraType.FrontFacing;
if (!PhotoCamera.IsCameraTypeSupported(cameraType))
    cameraType = CameraType.Primary;
    MessageBox.Show("Cannot find a camera on this device");
this.Camera = new PhotoCamera(cameraType);

In the above code, the PhotoCamera is initialized. Once initialized, ou can set the Camera photo streams to an element in the screen. To do that, we put a border and directly write the stream using VideoBrush.

<Border x:Name="cameraView" BorderBrush="Black" BorderThickness="5" Grid.Column="0">
           <VideoBrush x:Name="cameraBrush" />

Here the background of the border is filled using a VideoBrush. Now to set the CameraStream to the background of the Border, we simply write as :


Now to capture an image using the PhotoCamera, we call


The above code generates CaptureImageAvailable and CaptureThumbnailAvailable events. When the image is available you can write the data directly from the stream to a disk file.

private void Camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
     Deployment.Current.Dispatcher.BeginInvoke(() =>
         MediaLibrary ml = new MediaLibrary();
         ml.SavePictureToCameraRoll(string.Format("{0:yyyyMMdd-HHmmss}.jpg", DateTime.Now), e.ImageStream);

In the above code, you can see the Image when available after CaptureImage is called, is saved to CameraRoll folder of MediaLibrary. The e.ImageStream will hold the image that is been captured from PhotoCamera object. Using this API, you can capture images continuously and add it to the application and/or disk.

I hope this post will come handy. Will post more about PhotoCamera in subsequent entries. Stay tune.

Working with PhotoChooserTask in Windows Phone

Even though we have CameraCapture Task to deal with camera, there is another Chooser available as well, which can take Picture either from MediaLibrary or directly from Camera. The PhotoChooserTask helps in getting an image from the Picture / Media Library locations. The PhotoChooserTask, just like any other Tasks is listed under namespace Microsoft.Phone.Tasks and is inherited from ChooserBase<PhotoResult>, this will ensure that the Task is invoked as a Chooser and the result will be received by the Completed event when choice is made, just similar to CameraCapture.

var photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += (s, e)=>{
    if(e.TaskResult == TaskResult.OK)
        myImage.Source = new BitmapImage(new Uri(e.OriginalFileName));

The above code will show the photoChooserTask and upon selecting the Photo, it will show the picture on myImage control placed on the XAML.

PhotoChooser also allows you to specify ShowCamera, which can invoke the CameraCaptureTask directly from inside of the PhotoChooserTask and select the Photo Captured from camera.

photoChooserTask.ShowCamera = true;

Other than that, you can also set the maximum PixelHeight and PixelWidth of the image choosen from the PhotoChooser. For instance,

photoChooserTask.PixelHeight = 50;
photoChooserTask.PixelWidth = 50;

I hope this code will help. Thank you for reading.

Working with CameraCaptureTask in Windows Phone

Working with Camera in Windows Phone environment is a common requirement. Almost 25% of the apps in the store uses Camera capture on the app. CameraCaptureTask is a common Task available to the Windows Phone device which can capture camera from an app by launching the basic image capture tool present on the Windows Phone environment and take a picture and give the bytes to you. Here is now you can implement it.

var cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += (s,e) => {
    if (e.TaskResult == TaskResult.OK)
         System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
        myImage.Source = bmp;

The above code creates an object of CameraCaptureTask and invokes its Show method. The Show method will launch the Camera Task on the phone and when user captures the image, it will send the Image bytes to the Completed event. Inside the Completed event, we can have the Image stream available as e.ChosenPhoto. Here we simply displayed the stream in myImage control.

You can take the stream and do whatever you feel. For instance you can save the image in MediaLibrary using the following code.

byte[] ibytes = new byte[(int)e.ChosenPhoto.Length];
e.ChosenPhoto.Read(ibytes , 0, ibytes .Length);
e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
MediaLibrary library = new MediaLibrary();
library.SavePicture("myPhoto.jpg", ibytes );

The above code will save the image as myphoto.jpg to the Picture library. You can also pass the image stream to a WriteableBitmap to modify the content.

 WriteableBitmap writeableBitmap = new WriteableBitmap(200, 200);

I hope this will help you while dealing with Photo based applications in Windows Phone. Thanks for reading.