Sunday, May 20, 2012

The unsung hero, Volatile keyword: - c# threading

The unsung hero, Volatile keyword: - c# threading


My mad and blind love with c# threading


When I first saw c# threading code, I just falled in love forever. As days passed by the power and simplicity of “System.Threading” namespace converted my love in to blind love.

Thread t1 = new Thread(SomeThread);
t1.Start(o1);

In case you have not still fallen in love and new to c# threading, you can start looking at my c# training threading video from here.


















The blind love was but obvious because in today’s modern world parallel task execution is compulsory component.My love helped me to please users with mind blowing UI interfaces, multi-threaded batch processes, until one day…..

End of blind love with c# threads
























But one fine day my love with c# thread’s had a bump.I had two threads running and both where updating the same local variable.  The updation done by one thread was not visible to the other thread.

Let me detail what I am saying. I had create a local variable called as “_loop” as shown in the below abstract code snippet. This variable was set to ‘true’ by default.


class Program
{
bool _loop = true;

…        
}

In the same application I had created one function called as “SomeThread” which will run until the “_loop” is true.

private static void SomeThread(object o1)
{
….
….
while (o._loop)
{}
}

From the main thread I was spawning this some thread which was running the loop continuously. In this main thread I was setting the “_loop” to false. In other words the infinite loop of “SomeThread” should stop and exit…VOILA it did not.

static void Main(string[] args)
{
Thread t1 = new Thread(SomeThread);
t1.Start(o1);
o1._loop = false;
….
….
}

Below is the complete source code, you download and see it for yourself. https://skydrive.live.com/redir?resid=658DB05866C4E8A3!257&authkey=!ABOTw_YQ_czfnNc

bool _loop = true;
static void Main(string[] args)
{
            Program o1 = new Program();
            Thread t1 = new Thread(SomeThread);
            t1.Start(o1);
            Thread.Sleep(2000);
            o1._loop = false;
            Console.WriteLine("Value Set to false");
}
        private static void SomeThread(object o1)
        {
            Program o = (Program)o1;
            Console.WriteLine("Loop Starting...");
            while (o._loop)
            {}
            Console.WriteLine("Loop Stopping...");
        }

If you run the above code you can see the infinite loop starting, but I does not end even if the value was set to “false”.


You can also see the actual video demo of the code by clicking on c# training for threading .
Note :- When you run the code ensure that you have selected release  with CNTRL + F5 pressed.


Why did my love ditch me:- Local Thread memory storage and synchronization


After so many years of successful relationship it was difficult to believe this unexpected behavior. So I started googling to get reasons for it.

After long hours of reading, I was stunned that there are two kinds of memory we have to deal when it comes to threading.

One is the main memory where our variables are allocated and the thread also has his own local memory…SURPRISED, same here.

In other words the “_loop” is present at three places one in the main memory and second in the local memories of “mainthread” and “somethread” functions.

When the program kick starts the “_loop” is set to true. So all the memory storages have “_loop” set to true. See the below visual representation.


As the program runs the main thread set the value to false. This updation is done in the local memory of “mainthread” and main the memory, but it does not update the local memory of “SomeThread”. So the “SomeThread” function still sees the stale value and keeps running in a loop.

Below is a visual representation of how things look internally at various points.



The unsung hero: - Volatile keyword
















All relationships have problem, we just need to adjust, find solution and move with life. I was definitely in no mood of leaving c# threading after such a wonderful relationship.

The solution to get around this multiple memory storages was “VOLATILE” keyword.

If you declare your variable as volatile the thread tries to access values from main memory rather than from his local memory where data is stale. It does slow down a bit but it addresses this big confusion.

See it yourself, take the same source code and change the “_loop” variable to volatile as shown in the below code snippet and run it.

class Program
{
  volatile bool _loop = true;

Ensure that you select mode “release” and hit control + f5 to see the expected behavior.








Feel and See it yourself

In case you want to see it live what I have said in this blog see the video below
http://www.youtube.com/watch?v=DZUXDSEuqek

You can also see it yourself by downloading the code from the below link.

I am trainer by profession, interested in c# training , click here c# training .

Friday, May 18, 2012

UML Training: - Elaborate all types of diagrams in UML(Unified Modeling Language)?

There are nine types of diagrams in UML:-

Use case diagram:
They describe "WHAT" of a system rather than "HOW" the system does it. They are used to identify the primary elements and processes that form the system. The primary elements are termed as "actors" and the processes are called "use cases". Use Case diagrams shows "actors" and there "roles".

Class diagram:
From the use case diagram, we can now go to detail design of system, for which the primary step is class diagram. The best way to identify classes is to consider all "NOUNS" in use cases as classes, "VERBS" as methods of classes, relation between actors can then be used to define relation between classes. The relationship or association between the classes can be either an "is-a" or "has-a" relationship which can easily be identified from use cases.

Object diagram:
An object is an instance of a class. Object diagram captures the state of classes in the system and their relationships or associations at a specific point of time.

State diagram:
A state diagram, as the name suggests, represents the different states that objects in the system undergo during their life cycle. Object change in response to certain simulation so this simulation effect is captured in state diagram. Therefore, it has a initial state and final state and events that happen in between them. Whenever you think that some simulations are complicated, you can go for this diagram.

Sequence diagram:
Sequence diagrams can be used to explore the logic of a complex operation, function, or procedure. They are called sequence diagrams because sequential nature is shown via ordering of messages. First message starts at the top and the last message ends at bottom. The important aspect of a sequence diagram is that it is time-ordered. This means that the exact sequence of the interactions between the objects is represented step by step. Different objects in the sequence diagram interact with each other by passing "messages".

Collaboration diagram:
A collaboration diagram groups together the interactions between different objects to fulfill a common purpose.

Activity diagram:
Activity diagram is typically used for business process modeling, for modeling the logic captured by a single use case, or for visualizing the detailed logic of a business rule. Complicated process flows in the system are captured in the activity diagram. Similar to a state diagram, an activity diagram also consists of activities, actions, transitions, initial and final states, and guard conditions. However, difference is state diagrams are in context of simulation while activity gives detail view of business logic.

Deployment diagram:
Deployment diagrams show the hardware for your system, the software that is installed on that hardware, and the middleware used to connect the disparate machines to one another. It shows how the hardware and software work together to run a system. In one, line its shows the deployment view of the system.

Component diagram:
The component diagram represents the high-level parts that make up the system. From .NET angle point of view, they form the "NAMESPACES". This diagram depicts, at a high level, what components form part of the system, and how they are interrelated. Its shows the logical grouping of classes or group of other components.

See the following video on UML diagram: -



Click to get UML Training

Regards,

Get more UML training stuffs from author's blog

Tuesday, May 15, 2012

C# Training: - Elaborate various types of IIS isolation levels?

IIS has three level of isolation:-

LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects everyone.

Figure: - LOW IIS process scenario

Medium (Pooled):-
In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running.

Figure: - Medium pooled scenario

High (Isolated):-
In high isolated scenario every process is running is there own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.

Figure: - High isolation scenario

See the following video on ASP.NET4.0 Redirectpermanent: -



Click to get C# Training

Regards,

Get more C# training stuffs from author's blog

Thursday, May 3, 2012

ASP.Net Interview questions: - Mention differences between ‘Server.Transfer’ and ‘response.Redirect’?

Following are the major differences between them:-

‘Response. Redirect’ sends message to the browser saying it to move to some different page, while server. Transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in ‘server. Transfer’ there is no round trip while ‘response. Redirect’ has a round trip and hence puts a load on server.

Using ‘Server. Transfer’ you cannot redirect to a different from the server itself. Example if your server is www.yahoo.com you cannot use server. Transfer to move to www.microsoft.com but yes, you can move to www.yahoo.com/travels, i.e. with in websites. Cross server redirect is possible only by using Response. Redirect.

With ‘server. Transfer’ you can preserve your information. It has a parameter called as “preserveForm”.Therefore, the existing query string etc. will be able in the calling page.

If you are navigating within the same website use “Server. Transfer” or else go for “response.Redirect ()”

See the following video on ASP.NET4.0: -



Click for more ASP.NET interview questions

Regards,

Visit for more Authors’ blog on ASP.NET interview questions

Wednesday, May 2, 2012

Strings are from earth and StringBuilder from mars.

Introduction


I was happily married to string for a long time until I came to know the reality that “Strings are immutable” and not suitable for all scenarios. Recently I was working on a heavy HTML parser application and the program used to go out of memory frequently. The completely HTML parsing logic was using string variables.

After reading around I came to know the main reason was the immutable behavior of string. Immutable means once the data is assigned cannot be changed.

For instance if you are looping using a string variable like the code given below. Every assignment to the string creates new copies of variables and the previous copy is sent for garbage collection. So the below for loop generates different memory copies of data and the recently created is the current value.

   

Now you must be wondering why this absurd behavior. Any lame person (like me) can conclude this is not efficient and neither looks logical.

The sacrifice for thread safety


Before I start with the solution I wanted to understand why Microsoft team thought about this weird behavior. Thanks to http://stackoverflow.com/questions/2365272/why-net-string-is-immutable things started looking logical.

If you are using string variables in multithreaded scenarios every thread modification will create new copy of memory ensuring that you do not land in to multi-threaded issues. In other words thread safety is built-in by itself when new copies of data are created.

Not all work on ships


The next thing which started itching me is what if my application is not multi-threaded. What if my main motive is to save memory resources and ensure that I do not go out of memory issues?. Here’s comes the hero from mars “StringBuilder”.

“Stringbuilder” are not immutable, in other words if you change the variable data the same memory location is modified. VOW, that looks lot of memory saving during heavy concatenation operation as compared to string.

 

I wanted to see for myself that earth is flat


As a curios developer it was difficult for me to digest that internally string creates different copies of data. Out of curiosity I downloaded the CLR Profiler and ran two test of code as shown below.

One for string as the below.

string x ="";

for (inti = 0; i< 10000; i++)
{
x = "Shiv"+ x;

}


 

One for string builder.

StringBuilder x = newStringBuilder();

for (inti = 0; i< 10000; i++)
{
x.Append("Shiv");

}



Watch the allocated bytes, 400235631 bytes is way greaterthan 136597bytes.

Watch the video below for the real demo


If you do not believe what I have written see the actual video demo as follows