Kit functionality in IBM Maximo EAM system

Categories: Maximo EAM Tags:

Async / Await and SynchronicationContext (C# .Net)

Following innocuous looking async / await code will cause deadlock.

private void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = LongRunningProcess();

  textBox1.Text = task1.Result;
}

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  );

  return txt;
}

To understand why, lets go into what await does in the above case.

1 Execution starts when the button is clicked and button1_Click event is fired on the UI thread.
2 The method, named LongRunningProcess, is invoked.
3 The lamda expression passed to Task.Run() executes in a separate thread (lets call it thread_B)
4 Now await keyword is encountered, rather than completing the rest of the method, control returns back to button1_Click event to continue execution after the call to long running method.
5 Calling task1.Result makes the current thread wait on thread_B to complete and provide the results. So UI thread is now waiting for thread_B to complete.
6 As thread_B completes the task, it has to run the remaining part of long running method. Run time ensures that this code executes on the right context. That is, if the initial part of long running method was executed on the UI thread, then remaining part will also be executed in the same thread context.
7 Therefore, thread_B now attempts to run the remaining part of long running method on UI thread, while UI thread is waiting for thread_B to finish.
8 As UI thread and thread_B are waiting for each other, this creates the deadlock.
How to avoid deadlock?

In this case, deadlock can be avoided by anyone of the following ways:

1- Use await keyword while calling long running method. This makes the button click event asynchronous also.

private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await LongRunningProcess();
}

2- Call ConfigureAwait(false), this will inform the run time that the remaining part of long running method doesn’t need to execute on the UI thread, it can continue running on the thread pool.

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  ).ConfigureAwait(false); //avoids the deadlock

  return txt;
}
Why thread contexts are synchronized?

Consider the UI Controls (Windows Forms or WPF), they are not thread safe. Therefore, any update to the UI controls must be done only from the UI thread. To take care of this, any remaining code after await keyword in an asynchronous method will also execute on the thread context which initiated the method call.

Similarly, in an ASP.Net application, running the code on same thread context is important because the Culture, Principal and other information of the request are stored in the thread.

How thread contexts are synchronized?

To manage all this tricky context synchronization, we have SynchronizationContext class in .Net. There are framework specific implementations (derived classes) for Windows Forms, WPF/Silverlight and ASP.Net which handle the SynchronizationContext in their own ways for the framework to function properly.

The Windows Forms implementation uses Control.Invoke method to accomplish this (more details here). For ASP.NET, execution takes place on a different thread but the context is captured and passed on to the new thread.

There is an excellent article on MSDN regarding the SynchronizationContext which I recommend for details.

 

Creating and Consuming Async methods (C# .Net)

The code we want to run asynchronously could either be CPU-bound or IO-bound. CPU-bound code keeps the CPU busy, requiring intensive processing, calculations etc. On the other hand, IO-bound code frees up the CPU while waiting for an IO operation to complete, for instance, get some data from a web service. Both kinds of asynchronous methods are illustrated below.

 

 Creating Asynchronous method

 

CPU-bound Async method
public async Task<string> OurMethodAsync()
{
  string x = await Task.Run(() =>
    {
      // performs CPU intensive work
      return LongRunningTask();
    });

  return x;
}

Above method doesn’t do anything special. Rather than performing the work itself, it creates a thread and delegates the work to it. It will not make the task run faster, in fact, it may take more time due to multi-threading overhead. One reason to do things this way is to free the calling thread and not keep it busy for long time. This is required in case of User Interface threads, for instance.

 

IO-Bound Async method

For IO operation such as working with file system, requests to web servers etc., .Net framework already provides us with methods which run asynchronously. These methods uses lower levels OS calls to provide asynchronous behavior for blocking IO operations.

Below is our asynchronous method which uses .Net Framework’s WebClient.DownloadStringTaskAsync method.

public async Task<string> GetWebPage(string url)
{
  var webClient = new WebClient();
  string txt = await webClient.DownloadStringTaskAsync(url);

  return txt;
}

 

 Consuming asynchronous method

 

Consuming asynchronous method with await
private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await GetWebPage("http://www.yahoo.com");
}

 

This button click event consumes the IO-bound async method defined above. If GetWebPage method is taking a long time, the control will return back to the caller method. Once results of GetWebPage are available, execution will start again with the instruction after await keyword. This will ensure that the event does not block the UI thread.

Calling asynchronous methods concurrently

We can also use asynchronous method to run tasks in parallel.

private async void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = GetWebPage("http://www.yahoo.com");
  Task<string> task2 = GetWebPage("http://www.google.com");

  await Task.WhenAll(task1, task2);

  textBox1.Text = task1.Result;
  textBox2.Text = task2.Result;
}

 

Notice we are not using await keyword now when invoking GetWebPage method. This causes the return type to change also, we are expecting Task<string> rather than string object.

The flow control is also very different. If GetWebPage is blocking, the control doesn’t return to the caller method, rather execution continues to the next statement in the event.

We have await in the third line which will relinquish control to the caller method if task1 or task2 are not completed yet. When the result of the two tasks are available the last two lines of code are executed on the UI thread.

Keeping UI Responsive (C# .Net)

May 25, 2014 1 comment

The User Interface (UI) becomes unresponsive when a time taking operation is executed during an event.

Consider the following button click event where I have simulated a time taking operation by calling Sleep method. In a real scenario, it could be some processing which produces the result to be shown back on the user interface.

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Calculating result…";
   // long running operation simulated through Thread.Sleep
   System.Threading.Thread.Sleep(5000);

   textBox2.Text = "Final result";
}

 

Keeping UI responsive through System.Threading.Tasks.Task

To keep the UI responsive, we can spawn a new thread to perform the time taking operation. Earlier, we used to do it with System.Threading.Thread but now we have more convenient Task class from TPL (Task Parallel Library) in .Net.

private void button1_Click(object sender, EventArgs e)
{
   // do initial UI update
   textBox1.Text = "Calculating result…";

   // spawn a new thread for the long running operation and final UI update
   Task.Run(() =>
      {
         System.Threading.Thread.Sleep(5000);
         // unsafe call to UI control
         textBox2.Text = "Final result";
      });
}

 

If we run the above code in debug mode, we get the following exception:

image

UI controls are not thread-safe, therefore, call to the UI should only be made from UI thread which created these controls.

The way around this problem is to use Invoke method of the control and pass it a delegate which performs the required UI changes. Invoke method will ensure that the delegate is executed on the UI thread.

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Calculating result…";

   Task.Run(() =>
   {
      System.Threading.Thread.Sleep(5000);

      // using Control.Invoke
      Action act = () => textBox2.Text = "Final result";
      textBox2.Invoke(act);
   });
}

This will keep the UI responsive in a thread safe way.

 

Keeping UI responsive using async / await

Another way of doing this is through async / await keywords.

private async void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Started";

   await Task.Run(() => System.Threading.Thread.Sleep(5000));

   textBox2.Text = "Final result";
}

 

This code will achieve the same results as above.

With async / await, the code looks more synchronous and readable. As await keyword is encountered, a new thread is started for processing the task and the method returns the control back to the caller (this ensures that the UI thread is free and responsive). Once the task is completed, rest of the code for the click event is executed on the UI thread. Behind the scene, compiler generates complex state machine logic to make this happen seamlessly.

Code Snippet: PL/SQL Cursor inside Procedure or Anonymous Block

CREATE OR REPLACE PROCEDURE LOAD_DATA AS
/* replace the above line with DECLARE to have anonymous block */

  A_VAR VARCHAR2(30) := 'A Variable';

  CURSOR CUR_ST IS
  SELECT ST_ID, DESCRIPTION, ST_TYPE from SAMPLE_TABLE;
  /* SQL Query for defining cursor */

BEGIN

FOR CUR IN CUR_ST LOOP

  /* Looping... add main logic here */
  IF CUR.ST_TYPE = '1' THEN
    INSERT INTO OTHER_TABLE (OT_ID, DESCRIPTION) 
    VALUES(CUR.ST_ID, CUR.DESCRIPTION);
  ELSE
    A_VAR := 'SKIPPING';
  END;

END LOOP;

COMMIT;

EXCEPTION
  WHEN OTHERS THEN
    /* Do error handling here */
    /* Remove the EXCEPTION block for exceptions 
       to show up outside of procedure */
    A_VAR := 'ERROR';
    ROLLBACK;

END LOAD_DATA;
Categories: Oracle Tags: ,

Reading eBooks – Finding the right reader

Over the years, I have started doing more and more of my reading on electronic devices. In the PC era, Adobe PDF was the format of choice for delivering and reading e-books. But with the variety of devices and form factors in use now, there has been a shift towards ePub and mobi formats. These formats offer reflowable content, rather than fixed pages of PDF. PDF is more suited for printing while ePub and Mobi are focused on making documents readable on different screen sizes. I explored various options for consuming ePub files on PC, Mac and tablets including Apple’s iBooks, Adobe Digital Editions, Calibre, Readium and others.

iBooks

I found Apple’s iBooks to be the most pleasing to use. It has the right options in just the right places. It is available on Mac OS and iOS. But the drawback is: there is no option to get your notes and highlights out of iBooks and take them with you to, let’s say, a Windows machine. There is a third party software that extracts notes and bookmarks out of iBooks but it only works on iPad and iPhone, not on Mac. Due to this limitation I dropped the idea of using iBooks.

Adobe Digital Editions

Digital Editions is available for both Mac and Windows. It stores the notes and highlights in a separate file at C:\Users\<user>\Documents\My Digital Editions\Annotations. DropBox can be used to sync these files across Mac and Windows. ADE was the first software I downloaded and might not have gone further to try any other reader but there is a bug in current version of ADE (v 2.0.1) which compelled me to look elsewhere. The text rendering is terrible if you keep your side bar open. It took me some time to figure this out that the side bar is causing the awful rendering of text. Side bar contains things like notes and bookmarks, if you keep it closed then the content is rendered properly.

Others

I wanted to try Amazon Kindle also, it is available for all popular desktop and mobile platforms. But Amazon doesn’t allow Kindle downloads outside United States and few other countries.

I tried a few other readers available on internet but all of them suffer from one of the two shortcomings. Either they are buggy and have not been updated for a long time or they don’t provide the functionality to take notes and highlight content while reading.

Finally

After looking at these alternatives, I decided to continue with my current method:
– Use PDF files, this ensures that all my notes and highlights are within the book and can be easily moved around
– Sync PDF which I am reading currently through Google Drive or DropBox

Besides popular DropBox, Google Drive and SkyDrive, a nice cloud sync option is acrobat.com which offers about 10 GBs of free cloud storage. On the positive side, it is integrated with Adobe Acrobat Reader which is available for all desktop and mobile platforms. But the synchronisation is not as robust as DropBox and others.

In case, I just have the ePub file, Calibre is a good tool to convert to PDF and to many other formats for that matter. I found it to be better than other options like http://www.zamzar.com/convert/epub-to-pdf/‎. Calibre is a ePub reader also but it doesn’t allow note taking.

Categories: Uncategorized Tags:

Udacity’s ‘Introduction to Physics’ course

February 2, 2014 Leave a comment

Took ‘Introduction to Physics’ course at Udacity. It is a beginner level course and I have skimmed through most of it. But what kept me going till the end is the extremely engaging way in which it is taught. Every lesson, you take one important Physics problem and try to solve it. You make progress in small steps by learning required techniques and mathematics. Interactive nature of the platform always makes you think by asking questions before introducing new concepts. On top that, all this is linked with the history of the problem, who solved it and how?

The course has 7 lectures:

Lecture # 1: Circumference of Earth

The Greek philosopher, Eratosthenes (276 BC – 195 BC), was the first person to calculate the circumference of earth with remarkable accuracy. He used geometry and trigonometry to figure this out.

He only needed to take following measurements for his calculation:

  • Length of the shadow cast by an object A at noon at location X.
  • Height of the object A.
  • Distance of location X to the nearest location where sun doesn’t cast any shadow at noon.

See the diagram and link below for details.

Method of Eratosthenes

(Source: http://www8.svsu.edu/~lgreed/PartGrant7illust.htm)

 

Lecture # 2: Speed of freely falling object

Aristotle had following view on this:

  • Objects fall at constant speed.
  • Speed is directly proportional to mass of object.

It was Galileo who found that the distance covered by a falling object is directly proportional to the square of time it has been falling (i.e. objects fall with constant acceleration irrespective of their mass).

 

Lecture # 3: What causes motion?

The prevalent view before Galileo and Newton was Aristotelian. According to which there is one set of laws governing heavenly bodies and a different set for bodies on earth.

Newton through his laws of motion asserted that both heavens and the earth follow the same laws. And the apple falling from a tree or moon orbiting the earth do so under the influence of same force.

 

Lecture # 4: Keeping Holland Dry

 

image

This lecture is about Archimedes Screw and the basic principles behind its working. It builds on the understanding of force from previous lectures and introduces simple machines: Inclined Plane, Pulley and Lever. Simple machines enable us to trade off the force required to lift or move things with the distance. For example, using an inclined plane to move something to a higher level will require less force but we need to push it for a longer distance.

Next, the concepts of Work, Energy and Power are introduced.

  • Work = Force * Distance
  • Work = Change in Energy
  • Power = Work / Time
Work Energy Theorem 
 

Finally, the Law of Conservation of Energy is discussed with the example of roller coaster ride. During the ride, energy changes its form between kinetic and potential with some of the energy lost due to friction as heat.

 

Lecture # 5: Lost at Sea

Problem of this lecture is how to measure latitude and longitude?

image

Latitude is relatively easier to calculate while longitude is much trickier.

When sun is at the highest point in the sky and it is equinox, the latitude can be calculated as explained in the first lecture.

For calculating Longitude, we need to keep track of time. Galileo attempted to measure time by observing transit of Jupiter’s moon but the idea was not very fruitful due to the difficulties involved.

The answer lies in Simple Harmonic Motion.

Simple_Harmonic_Motion_Orbit

Elastic Potential Energy

pelasimage

k = Spring Constant

Lecture discusses the discovery of Pendulum by Galileo and invention of Pendulum Clock by Christiaan Huygens.

Longitude can be measured by comparing the time on ship to the time of a known location. Pendulum clocks can be used to reliably measure time and hence calculate longitude.

 

Lecture # 6: Lightning Strikes

 

image

Lightning is an electrical phenomenon. This was not very clear in 18th century. The link between lightning and electricity was there in the literature but it was Benjamin Franklin (17-Jan-1706  to  17-Apr-1790) who emphasized this link and developed lightning rods which prevented buildings from burning due to lightning strikes.

 

This lecture talks about basics of electricity with particular focus on lightening rod and how it grounds the electric current keeping buildings safe.

 

Lecture # 7: Special Relativity

This is brief teaser to Special Relativity explaining the following two postulates of the theory and how they lead to bizarre conclusions like time dilation.

  • Laws of Physics are same in all inertial frame of reference
  • Speed of light constant regardless of the frame of reference

de Sitter double star experiment is explained as test of Special Relativity.

 

It concludes with a final exam where you can test your problem solving skills using the knowledge gained through the course. There are couple of bonus lectures also about ‘simple harmonic motion’ and ‘why can’t we open windows on an airplane’.

Categories: Uncategorized Tags:
Follow

Get every new post delivered to your Inbox.

Join 42 other followers