Sunday, 10 January 2010

Task ( TPL ) and Threads - Are they different ?

It took me some reading to understand that Thread and Task - in the context of the Task Parallel Library ( TPL )- are not comparable. Or in other words they represent an entirely different manner of doing the parallel computing in the world of .Net. Task, which belongs to the System.Threading.Tasks library in .net 4.0 works directly with the ThreadPool through a framework exculsively implemented for that purpose. This framework is nothing but the TaskScheduler .

Unlike the legacy multi-threaded .net applications, wherein you can new up as many or atleast a couple threads till no more gain in application performance, in .Net 4.0 it is totally a discretion of task scheduler. This means that the code below - though it is naive - will not start a new THREAD each time when I am newing up Tasks in a for loop like below

for(int i = 0; i < 100 ; i++)
{
Task.Factory.StartNew(() =>
{ // Do Work.
}
}

The same is applicable to the statement below, but here it works the other way round

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

All we are doing above is to invoke the two methods DoSomeWork() and DoSomeOtherWork() in parallel. Now that does not mean that two different tasks will ALWAYS be created for this purpose, once the request goes to the taskscheduler It will know that it needs to spin two threads, not related to creating two new tasks.
Having said that it does not mean that if I have three methods like below , TaskScheduler will spin three threads. It might as well serve the request by two threads only.

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork(), , () => DoSomeMoreOtherWork());

Taking another example, if you execute the code below and open the Parallel Tasks and Parallel Stacks window, you can clearly see that threads and Tasks are totally non-interrelated with TaskScheduler using it own optimisations to decide when to start a new thread.

Parallel.For(0, nums.Length, () => 0, (j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
(x) => Interlocked.Add(ref total, x)
);

As msdn rightly says

"With the TPL, think in terms of tasks, not threads."

Happy Coding

Wednesday, 13 August 2008

IIS Keep - Alive

Lately I have been mulling about with the an error that some of the clients were getting from the webservice hosted on the servers in my organisation. Yes! the much talked about ...

The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.

TBH, I had never seen this error before this juncture and could hardly figure out where the link was broken. I struggled for few days, struggling to find out a solution to it and then, like my many fellow developers came across the Keep-alive functionality inside IIS . Again it was a conundrum to me, as I had never played with this aspect of IIS much and being a live box, I had to be double sure what I am doing. It boiled down to understanding this Keep- Alive thingy and I thought I should share it within the community. A lot of articles talk about jow it turn it off and on but it was hard for me to find that why turn it off or on and why does IIS need it .

The answer is to be found in the life cycle of asp.net application or for that matter any web application . What happens when a page request comes to IIS ?!? . I think most of the folks know about all this stuff but I don't want to talk about the bigger picture here.

Its all inside the ISAPI extenstions that we get the answer to this .....

The following events occur when IIS receives a request that maps to an ISAPI extension:


  • IIS loads the DLL, if it is not already in memory. When the DLL is loaded, Windows automatically calls the optional DLL entry/exit function (usually DllMain). IIS then calls the extension's GetExtensionVersion entry-point function.

  • IIS performs minor preprocessing on the incoming request.

  • IIS creates and populates an EXTENSION_CONTROL_BLOCK structure to pass request data and callback function pointers to the extension.

  • IIS calls the ISAPI extension's HttpExtensionProc function, passing a pointer to the EXTENSION_CONTROL_BLOCK structure created for this request.

  • The ISAPI extension carries out the actions it was designed to perform: for example, reading more data from the client (as in a POST operation), or writing headers and data back to the client.

  • The extension informs IIS that it is finished processing the request by exiting the HttpExtensionProc function. For synchronous operations, the function returns the HSE_STATUS_SUCCESS return code; for asynchronous operations, the return code is HSE_STATUS_PENDING. For more information about asynchronous operations, see Asynchronous I/O Processing.

  • IIS performs cleanup on the connection used for the request, after which it closes the connection if Keep-Alive functionality is not enabled.

And here is when the IIS Keep-Alive settings are effectively going to determine whether the connection needs to be closed.


  • Once the ISAPI extension is no longer needed, IIS calls the TerminateExtension function, if the extension provides one. If IIS is configured to cache ISAPI extensions, TerminateExtension is not called until the IIS Web server is shut down or restarted.

Monday, 11 August 2008

LINQ - A hand at XML Linq

A while ago, I happened to play around with LINQ - was working on AJAX and came across a cool way to access the tables inside a dataset. Below is a snippet of code I tried


The one line code can be as below

The code selects the rows in a table into a collection depending on the where clause. I am fan of stuff like this !! Write me if you want me to explain :)

AJAX - Calling webservice from Client Side and populating the returned XML in controls

Another interesting and common task you would come across while working with AJAX is to call a service from client side, it is a brilliant thing to work with and a rich experience for the user. In crux, you make repeated calls to the database without postbacks and the entire call happens around the client with a relaxed server side. In a SOA architecture, this is a boon to the ASP.net technology and I just love doing it .


How to approach ....

1) Get your tool kit ready for the AJAX control by referencing AjaxControlToolkit.dll. You can grab a copy anywhere online and create the registration in you page.

2) Place a button which can fire the event to call the service, here the main bit of code is the ShowAmendDetailsModalPopup() - I am using a modal popup extender here to call a modal popup , which in turn will be bound to a panel control populated with the details furnished by the webservice.

OnClientClick="ShowAmendDetailsModalPopup();

3) Create the webservice named webservice.asmx with whatever method you want to use on the button click. Make sure you have marked the webservice with the
[ScriptService] attribute, because script manager will not be able to discover your service otherwise.

4) Get the script manager ready in the below forrmat with the reference to all the services being used by the button, here the Service we will be using in the Webservice.asmx

5) Create a ModalPopup extender like below and set the attributes accodingly.
6) Okie, so now you are almost done with the groundwork to start using the service .

7) ShowAmendDetailsModalPopup() javascript function is to be defined for showing the modal popup and calling the webservice.


If you have noticed above , we pass the method used to handle the turn values from webservice as an argumnet in this case it is called DisplayResult() and is being used to manipulate the XML generated by the webservice.. COOL Stuff !!
That is it , once you click the button everything is done on the client side and you see the details in a modal popup :)



AJAX - Dynamic Updatable Slider control

A few weeks back one of the project managers in my organisation wanted to migrate a project from windows to thin client environment and as he had seen me boasting about the AJAX framework most of the times, he asked me to do this small task for him . A dynamically Updatable Slidder Control. This requirement was generated as part of a screen, which gathers the insurance deals and hence needs an adjustable upper and lower limit, which can be dragged and adjusted at will.

To dwell upon the same, the reuirement was to have two slidder controls and adjust one when the other is changed so that the total remains the same. Simple !! yeah it is, but still interesting.
Here's how you can approach it....
1) Get your toolkit ready for the AJAX framework - put the sciprt manager in place , reference the appropriate dlls ( this may not be required if you are working on ASP.net 3.0), Register the AJAXtoolkit tags on your page.


2) Drop a SliderExtender control on the page and define the necessary attributes as below







I won't be discussing the various attributes defined above but they can be found in this dictionary.
Thre interesting attribute here is BehaviorId . The BehaviorId property is used here to set the an ID value, which can be used to update the slider of the slider control dynamically depending on the calculation or any desired logic.

The TargetControlId is the id of the control which is used as the udrlying control to which the slider is bound so that the change events can be caputured. The SetValue() method is fired on the change of the slider which in turn fires the onChange() , because of the change in the value of the textbox underlying the slider as shown below.














This is about it and you can have have a control something like shown below , wherein if yoy update one value the other value gets updated by itself . Cool :) !!