Wednesday, September 30, 2015

Write in stone when someone does something good for you


Found this nice story in Internet, could not stop myself from sharing. Story credit goes to author.


A story tells that two friends were walking through the desert. During some point of the journey they had an argument, and one friend slapped the other one in the face.

The one who got slapped was hurt, but without saying anything, wrote in the sand “Today my best friend slapped me in the face”.

They kept on walking until they found an oasis, where they decided to take a bath. The one who had been slapped got stuck in the mire and started drowning, but the friend saved him. After he recovered from the near drowning, he wrote on a stone “Today my best friend saved my life”.

The friend who had slapped and saved his best friend asked him, “After I hurt you, you wrote in the sand and now, you write on a stone, why?” The other friend replied “When someone hurts us we should write it down in sand where winds of forgiveness can erase it away. But, when someone does something good for us, we must engrave it in stone where no wind can ever erase it.”

Tuesday, September 29, 2015

Cancel current HTTP thread on server from client



Yes, this is possible, if we gracefully handle server flow particularly in long running task. It’s obvious that your may not wait for a long running task in server. For example, you are running one long running select query and in middle user has cancel the http request. How to cancel? 

Simply press cross sign after or before address bar (based on browser) or If you refresh/navigate to another page, browser will automatically send one cancelation signal to current HTTP thread.
Let’s see, whether browser really cancel the current HTTP or not!

Here is my simple long running code.

public IActionResult Index()
        {
           
           System.Threading.Thread.Sleep(5000);
            return View();
        }

And in middle when of execution when I am just pressing cross sign, It’s getting cancel from browser’s





End. Now, Question is that, how to receive the signal in server and take decision accordingly? The implementation is very simple, just we need to pass CancellationToken parameter to action.

public IActionResult Index(CancellationToken token)
        {
           
            bool flag = token.IsCancellationRequested;

            System.Threading.Thread.Sleep(5000);

            bool afterCancel = token.IsCancellationRequested;


            return View();
        }

If you have some existing parameter, then add this at end of all parameter. Now, let’s run the example again. It’s showing false in flag variable when I am triggering HTTP.


Now, In time of Thread.Sleep() execution , I have cancelled the HTTP request and we are seeing that the afterCancel is flag is true now.