Search This Blog

Wednesday, 8 September 2021

The Life of Gossip - Log Kya Kahenge Syndrome - How to Deal with it - Inspired from true life stories

Audio + Video Narration for this blog


One often hears this:

I'm worried of setting a precedent. I mean, what will others think about me?

When I hear someone speak like this, I normally respond in hindi saying "Log kya sochenge,yeh bhi aap hi sochoge, toh phir bechare woh kya karenge?"

Let me translate it in English, trying to keep its humour intact,


If you start thinking what people will think about you, poor thing, what will they do? You would have lost them their only job that's Gossipping :-)


As long as what you are doing is righteous and has you with a clear conscience, its not wrong to set a precedent, is it?

==============================

To get to this point of level-headed thinking, seeing humour rather than getting worried about gossip-mongering, let me narrate to you a story.

This is the story of anyone, who treads an uncommon path. One can be sure to have these experiences atleast once in life.

What's important is what learning you take back from this experience.


==============================

Well, the narration ahead is part of several true stories.

The subjects of the story not only have a happy family, but also are treated with love and respect within the family and society. The names are changed to ensure privacy.


It so happened, Suhani an independent working professional & the would-be bride had only her old and retired mother as family. Suhani took the decision to get married only and only if the groom agreed to permanantly re-locate to her place. In India, it is a norm that the bride relocates to the husband's home after the ritual of Kanya-daan. Suhani dared to reverse this norm.


The bride's family were shocked and ashamed of Suhani. She became the talk of the town, family and friends in a negative sense. The groom's family spoke ill about the bride and bride's family as well. The groom Harshvardhan though surprised, decided to talk it out with Suhani. Suhani said that "..all I have is my mother, who would be left alone if I got married and relocated to your place." She also informed about her survey conducted on marriage, married women and their tryst to gaining respect, dignity and love in the in-laws place. In the balance, she told Harshvardhan, it would be risky to have her mother also relocate with her to the in-laws place, she might feel left out, what if she was ill-treated or not respected, it would affect our relationship. You have a large family, but all I have is only my mother. Harshvardhan being a mature and understanding guy, agreed to permanantly relocate with her.


The groom's family strongly opposed the marriage. The groom's relative Ms. Samiksha had openly criticized Suhani and her mother for such an upbringing. With a lot of efforts from Harshvardhan's parents and Suhani, this precedent was set, and the marriage took place.

The gossip with its added spices spread around the place for a long time.

    On the humourous side, one can say, If gossip were food, many people would be overweight! Wouldn't they?


Suhani and Harshvardhan dealt with a few emotional upheavels due to the gossip mongering. Harshvardhan suggested they leave the city and live elsewhere. Suhani was firm and advised not to run away because of gossips. They eventually started their family, giving a deaf ear to the gossip mongerers, and were happy with their course of life.


After a year or two, Ms Samiksha who had played a key role in criticizing and gossip-mongering about Suhani, had to have her daughter Sharmila married. Sharmila got married, but faced a lot of abuse at the hand of the in-laws. She returned to her mother's place. She was in a bad state. She informed her mother Samiksha, that she would only be able to sustain her marriage, if her husband relocated to her place. This time, as it was her daughter's life, Samiksha agreed to this change in norm. Sharmila's husband relocated himself, while Suhani helped her come out of her mental trauma.


The town which had been talking ill of Suhani, now started gossipping about Samiksha and her daughter. They started respecting Suhani for her help and criticizing Samiksha for her attitude towards Suhani. So Samiksha now was the element of gossip in the town, while Suhani was loved and respected.


Well, what do we learn from this story?

People's attitude changed, with changing situations

Things turned 180 degrees, the gossip elements changed

The ones who were criticized in gossip, were now revered. While the ones who created the gossip, themselves became an element of gossip.


Suhani continued her life, without indulging in counter-gossip. What was the result? People became curious, as to why she wasn't reacting.

As she chose to stay unbaised and deaf to gossip mongerers, knowingly or unknowingly, she also helped the person, who indeed had criticized and spread gossip about her.

Remember it takes a lot of effort to sustain gossip, but just one action to silence it.

You see, gossip ends at the ears of the wise person.


There are a lot of us, whether common man, celebrities, politicians or nations who are victimized through this strategy.

A lot of problems in the world would disappear, if we talked it out to each other, instead of talking about each other, Isn't it?


Hope this put's your perspective into clear light. Wishing you a great day and do stay tuned to Pearls of Wisdom!

Saturday, 12 June 2021

Symphony with Asynchrony - C#


Let me explain asynchrony to you in a simple way.

Assume there are two functions named Main() and ICanDoAJob(). Main() is a function that executes line-by -line in a sequential manner. If there is a function such as LongRunning() which takes about 2 minutes to complete its execution, then Main() can cause the application to hang for 2min.

Hence Main() decides to give the job of executing LongRunning() to the function ICanDoAJob(), on a condition that ICanDoAJob() will take care of executing LongRunning() without disturbing or interrupting the work execution of Main().

ICanDoAJob(), now works independently, while Main() executes his calls without waiting for LongRunning() until it executes. This is known as asynchrony.


  

How is this Asynchrony achieved?

 

To achieve this asynchrony, let’s understand how a resource is executed.

The OS memory manager allocates memory for a resource to run on memory. When this is done, a Process Id is assigned, and each resource running in memory (RAM) is called as a process. Process is usually a background service or an executable (.exe). For example, when you open Visual Studio, a process is created for its underlying exe which is “devenv.exe”. This can be viewed in the Task Manager (of Windows OS), as shown in the screenshot (A) below. You will observe that it is allocated with a ProcessId. Similarly, Each process has atleast one thread known as the Main thread, that executes the process. In a normal program, this is the Main() method. A Thread can be considered as an independently executing task. If the Main() thread now spawns additional such threads which execute asynchronously, and merge with the Main() after completion, then technically this is known as asynchrony. The total threads for a particular process can be seen in the Task Manager -> Performance Tab -> Open Resource Monitor. Please observe the screenshot (B) to understand how many threads are created for the process “devenv.exe



 

(A)                                

 


                                

 

                                                                                                            (B)


                                      

In .Net, if one wants spawn threads from the Main() method, it can be achieved using a class known as the ThreadStart() delegate. This is highlighted in the code block below.

1.  Thread thr = new Thread(new ThreadStart(() => {
2.                                          for (int i = 0; i < 10; i++)
3.                                                         Console.WriteLine($"Thread {i}");
4.                                       }));
5.              thr.Start();
6.   

Here, the developer needs to take care of thread management efficiently through code. As threads run independently, this can be a problem if the thread is not stopped or merged correctly.

With the advent of new features introduced in .Net the concept of “Tasks” is introduced with a garnish of two best friends introduced in the form of keywords “async … await”. Async & await can be understood by the analogy of husband (async) and wife (await). The wife brings in order and creates a disciplined routine. Similarly, await will see that a task running asynchronously runs in an ordered manner. When async is used without await, the execution will be in a haphazard manner. The wife is always with the husband. Hence, await (wife) cannot be used if a method is not marked as async (husband).

Hence technically, there is a class in the System.Threading namespace, called Task.

The unit of code (An anonymous Lambda / a named function) to be executed asynchronously is created as a Task. To mark this unit of code to run asynchronously, the method is marked as “async”.

If there are multiple such tasks executing independently, where the output of one TaskA is an input to TaskB, then it is important to await the completion of the execution of TaskA, before passing its output to TaskB. Here it is important to use the keyword “await”.

Is it important to use await with async? Can async be used without await? The quick answer is YES.

But, unless you mark a method as async, await cannot be used. This means, to use await, a method must be marked as async. But if a method is marked as async, await may or may not be added.

The syntax for creating a Task is as follows

1.  Task.Run(()=>{});
2.   

In the above code, Run is a function, that takes Action delegate as a parameter. Let’s now create a function that uses asyncawait and Task. The following program will print the text on the console.

1.  static void Main(string[] args)
2.          {
3.             Method1();
4.          }
5.  public static void Method2()
6.          {
7.              for (int i = 0; i < 25; i++)
8.              {
9.                  Console.WriteLine($"M2-{i} Method 2");
10.               }
11.           }
12.   public static async void Method1()
13.           {
14.               await Task.Run(() =>
15.               {
16.                   for (int i = 0; i < 1000; i++)
17.                   {
18.                       Console.WriteLine($"M1-{i} Method 1");
19.                   }
20.               });
21.  

The same can be done using a TaskFactory, which creates tasks from a pool of tasks.

1.              TaskFactory factory = new TaskFactory();
2.              factory.StartNew(() => Method2());
3.              factory.StartNew(() => Method3(9999));
4.   
5.              Task.Factory.StartNew(() => Method2());
6.   

Tasks can also be pre-created and stored in a collection. In this case, it is better to use a thread-safe collection, such as ConcurrentBag<>. To do so, we create Task objects and add them to a ConcurrentBag, and then execute it wherever required. Have a look at the code below.

1.  public static async void UseConcurrentBag()
2.          {
3.   
4.              ConcurrentBag<Task> taskBag = new ConcurrentBag<Task>();
5.              Task t1 = new Task(() => Method1());
6.              Task t2 = new Task(() => Method2());
7.   
8.              taskBag.Add(t1);
9.              taskBag.Add(t2);
10.    
11.               foreach (var t in taskBag)
12.               {
13.                   t.Start();
14.                   Console.WriteLine($"Id: {t.Id}, Status: {t.Status}, IsCancellable: {t.IsCanceled}");
15.               }
16.           }
17.    

The difference between a thread and a Task is, a task can be cancelled midway. This is done by adding a CancellationToken at the time of creation of the task. This CancellationToken object is generated from a CancellationTokenSource class object. View the sample code below.

1.  public static void UsingTaskCancellation()
2.          {
3.              //STEP 1: Initialize Cancellation token source to cancel a task
4.              CancellationTokenSource tokenSource = new CancellationTokenSource();
5.              CancellationToken token = tokenSource.Token;
6.              
7.              //Start a new task by passing the cancellation token
8.              Task t = Task.Factory.StartNew(() => {
9.                  int counter = 1;
10.                   while (!token.IsCancellationRequested)
11.                   {
12.                       Console.WriteLine(counter++);
13.                       Thread.Sleep(1000);
14.                   }
15.               }, token);
16.    
17.               //On any key pressed by user, cancel the task
18.               Console.WriteLine("======== Press any key to cancel this task ========");
19.               Console.ReadKey();
20.               tokenSource.Cancel();   //Cancels a running task
21.               Console.WriteLine("Task Cancelled");
22.           }
23.    

 Hope you get a headstart to asynchrony and enjoy your programming journey ahead.