Monday, January 5, 2015

Working with Geo Location Windows Phone 8.1

How to get the Geo location information in windows phone 8.1?

you have the GeoLocator class  in Windows.Devices.GeoLocation namespace .

First thing you have to make sure as a developer is to enable the location capabilities in the Package.appxmanifest as shown below .


Below is a sample code to fetch the Location information .
private Geolocator _geolocator = null;
async private void GetGeolocation()
{ 
  _geolocator = new Geolocator();
 // Desired Accuracy needs to be set
 // before polling for desired accuracy.
 _geolocator.DesiredAccuracyInMeters = 50;
 try 
 {
 // Carry out the operation
 Geoposition pos = await _geolocator.GetGeopositionAsync();
 }
 catch
 {
 /*Operation aborted Your App does not have permission to access location data.
 Make sure you have defined ID_CAP_LOCATION in the application manifest and that on your phone,
 you have turned on location by checking Settings > Location.*/
 //if the location service is turned off then you can take the user to the location setting with the below code
 await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
 }

}
** you can set the time out period to fetch the location information and also you can set the pool time interval before which the location API is called again.

Geoposition pos = await _geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(15));
**above piece of code says that if a request is made get the location information then the system will check the time interval since the last request was made , if the request is made with in 10 minutes then the last cached value will be returned , if not he new values will be fetched and also the API will be timeout if the request does not respond with in 15 minutes of the request .

How to Cancel a request made to get the Geo location information?

if you have requested for location information and for some reason you want to cancel the request all you have to do is use the CancellationToken Object in conjunction with the GeoLocator object as shown below.

private CancellationTokenSource _cts = null;
async private void GetGeolocation()
{
_geolocator = new Geolocator();
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Desired Accuracy needs to be set
// before polling for desired accuracy.
_geolocator.DesiredAccuracyInMeters = 50;
 try 
 {
  // Carry out the operation
  Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
 }
 catch
 {
  /*Operation aborted Your App does not have permission to access location data.
  Make sure you have defined ID_CAP_LOCATION in the application manifest and that on your phone,
  you have turned on location by checking Settings > Location.*/
  //if the location service is turned off then you can take the user to the location setting with the below code
  await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
 }
}
//Call this Method to cancel the current location access request
cancelGelocationRequest()
 {
 if (_cts != null)
 {
 _cts.Cancel();
 _cts = null;
 }
}

How to Track Location Changes?

If you want a real time info as soon as the user location changes then you have to subscribe to StatusChanged and PositionChanged Events of the GeoLocator object .

Below is the code snippet for the same .
private Geolocator _geolocator = new Geolocator();
TrackMyLocation()
{
 _geolocator.StatusChanged += _geolocator_StatusChanged;
 _geolocator.PositionChanged += _geolocator_PositionChanged;
}
void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
// will get a new GeoPostion object in the args paramter which gives the updated lat long values
}
void _geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
{
 //gives s postionstatus object with below values
 /* Ready
 Initilizing
 NoData
 Disabled
 NotInitilized
 NotAvalible
 */
}

Friday, January 2, 2015

Synchronizing Threads - Part 2


In the previous article we discussed about locking options in c# , in this article we will see the signaling methods , Signaling is a concept where is you notify a thread to continue its execution which is initially waiting  for some other thread to finish executing a section of code .

AutoResetEvent,ManulResetEvent,CountDownEvent,Wait and Pulse,Barrier are the options available for signaling threads in C#.

AutoResetEvent

AutoResetEvent is analogous to ticket turnstile or toll booth where in only one ticket lets one vehicle through and the toll gate is automatically closed .
a thread  is made to wait with the WaitOne keyword and a call to set lets the waiting thread to continue. below is the trivial example on how to use AutoResetEvent To signal .

class ThreadSignaling
    {
      static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
        static void Main(string[] args)
        {    new Thread(WaitingThread).Start();
            Console.WriteLine("Main Theard :simulating long running task");
            Thread.Sleep(3000);
            Console.WriteLine("Main Theard :sending signal using AutoResetEvent");
            autoResetEvent.Set();
        }

        private static void WaitingThread()
        {
            Console.WriteLine("WaitingThread:Enters in waiting mode -- ");
            autoResetEvent.WaitOne();
            Console.WriteLine("WaitingThread: the signal from a diffrent thread with AutoResetEvent");
            Console.ReadKey();
        }
    }

ManulResetEvent:

ManualResetEvent works more like a school gate where is once the gate us open all the students waiting are allowed to go through the gate , Calling waitOne  will block the thread and once Set is called all the threads that were block with WaitOne continues its execution at a time unlike AutoResetEvent Where one call to Set releases only one WaitOne Counter part ..

below is the sample code which demonstrates the same .
 class ThreadSignaling
    {
        static ManualResetEvent autoResetEvent = new ManualResetEvent(false);
        static void Main(string[] args)
        {
            new Thread(WaitingThread1).Start();
             new Thread(WaitingThread1).Start();
            Console.WriteLine("Main Theard :simulating long running task");
            Thread.Sleep(3000);
            Console.WriteLine("Main Theard :sending signal using ManualResetEvent");
            autoResetEvent.Set();
        }

        private static void WaitingThread1()
        {
            Console.WriteLine("WaitingThread1:Enters in waiting mode -- ");
            autoResetEvent.WaitOne();
            Console.WriteLine("WaitingThread1: the signal from a diffrent thread with ManualResetEvent");
            Console.ReadKey();
        }
        private static void WaitingThread2()
        {
            Console.WriteLine("WaitingThread2:Enters in waiting mode -- ");
            autoResetEvent.WaitOne();
            Console.WriteLine("WaitingThread2: the signal from a diffrent thread with ManualResetEvent");
            Console.ReadKey();
        }
    }

CountDownEvent(.NET 4.0 and above)

CountDownEvent allows a thread to wait till you get a configured number of signals from different threads before the thread continues . The thread gets blocked  by calling Wait and the signal is passed to the waiting construct by calling Signal .
below is a trivial example of CountDownEvent 
class ThreadSignaling
    {
        static CountdownEvent countDownEvent = new CountdownEvent(2);
        static void Main(string[] args)
        {
            new Thread(WaitingThread).Start();
            new Thread(SignalThread1).Start();
            new Thread(SignalThread2).Start();
            Console.ReadKey();
        }
        private static void WaitingThread()
        {
            Console.WriteLine("WaitingThread1:Enters in waiting mode -- ");
            countDownEvent.Wait();
            Console.WriteLine("WaitingThread1: Continued after reciving two signals from diffrent threads");
            Console.ReadKey();
        }
        private static void SignalThread1()
        {
            Console.WriteLine("SignalThread1:Simulating long running task ");
            Thread.Sleep(3000);
            countDownEvent.Signal();
            Console.WriteLine("SignalThread1: Sends the signal as the task is done ");
            Console.ReadKey();
        }

        private static void SignalThread2()
        {
            Console.WriteLine("SignalThread2:Simulating long running task ");
            Thread.Sleep(5000);
            countDownEvent.Signal();
            Console.WriteLine("SignalThread2: Sends the signal as the task is done ");
            Console.ReadKey();
        }
    }
Above we looked into simpler version of signaling, in the next article we will discuss about more powerful construct to achieve signaling for threads using Wait and Pulse from the Monitor Class and also discuss about Barrier which  is available for .net framework 4.0 and above .




Thursday, January 1, 2015

Synchronizing Threads - Part 1

What is Thread Synchronization?

There s a couple of context you want to consider when defining Thread Synchronization.

It  is a mechanism where in the critical section (code block or resource) is accessible to only one thread at a time.

It a mechanism where one thread waits for other thread  to finish executing before continuing with the execution .

failing to handle these will result in race conditions ,unpredictable results and dead locks.

lets go over the options available in c# to when working with thread synchronization .

If you want to limit the number of thread that can access a resource or block of code at a time ,then
your options are lock, Monitor,Mutex,SpinLock,Semaphore .

If you want to pause a thread's execution till you get a notification from other thread then your options are  AutoResetEvent,ManulResetEvent,CountDownEvent,Barrier, Wait and pulse .

In the first part of this post we will look at locking options C#.

Lock

It provides a very basic exclusive lock for a code block letting one thread access the code block
below is a trivial example for the same ..

public  class ThreadNotSafe
    {   int _v1 = 1;
        int _v2 = 1;
        public  void Execute() 
        {
            if (_v2 != 0)
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine("Result is " + _v1 / _v2);
                }                
                _v2 = 0;                 
            }
            else
            {
                Console.WriteLine("Invalid Operation");
            }        
        } 
    }

    static void Main(string[] args)
        {
           ThreadNotSafe unsafeObject = new ThreadNotSafe();
           Thread thread1 = new Thread(unsafeObject.Execute);
           Thread thread2 = new Thread(unsafeObject.Execute);
            thread1.Start();
            thread2.Start();
            Console.ReadLine();            
        }
The above Execute function seems safe as we are checking if _v2 is zero only then we proceed with the division , but when this method is accessed by two different threads more often then not you will end up with the divide by zero error.
 now the below code is thread safe with lock .

  public  void Execute() 
     {
       lock (this)
         {
             if (_v2 != 0)
                {
                    for (int i = 0; i < 100; i++)
                    {
                        Console.WriteLine("Result is " + _v1 / _v2);
                    }
                    _v2 = 0;
                }
                else
                {
                    Console.WriteLine("Invalid Operation");
                }
            }        
        } 

Monitor

The lock syntax discussed  above is a shortcut for Monitor.Enter and Monitor.Exit, The Monitor object offer more flexibility than lock like Monitor.TryEnter  which can return a bool value if the lock is already taken and you can also specify a timeout value if you  want to wait for sometime before trying to enter the code block. 
below is the sample for same where in  the  second thread try's to enter the critical section after waiting for two seconds .
   public  void Execute() 
        {
            if (Monitor.TryEnter(this,2000))
            {                
                try
                {
                    if (_v2 != 0)
                    {
                        for (int i = 0; i < 100; i++)
                        {
                            Console.WriteLine("Result is " + _v1 / _v2);
                        }

                        _v2 = 0;
                    }
                    else
                    {
                        Console.WriteLine("Invalid Operation");
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    Monitor.Exit(this);
                }
            }
       }
** More to explore on Monitor Object is Monitor.Pluse ,PluseAll ,Overloads of Monitor.TryEnter,Mintor.Enter.

What is Deadlock?

Is a situation where in one thread waits for a resource to be release held by the other thread, below is a trival example where is deadlock situation occurs .
public class Deadlock 
   {
       private static readonly object _lock1 = new object();
       private static readonly object _lock2 = new object();
       public void Deadlock1() 
       {
           lock (_lock1)
           {
               Console.WriteLine("i m in Deadlock1 with lock on _lock1");
               //simulate loong running proceess
               for (int i = 0; i < 10000; i++)
               {                   
               }
               Console.WriteLine("i m in Deadlock1 with lock on _lock1 i need access to _lock2");
               lock (_lock2)
               {
                   Console.WriteLine("i got _lock2");
               }
           }       
       }

       public void Deadlock2()
       {
           lock (_lock2)
           {
               Console.WriteLine("i m in Deadlock2 with lock on _lock2");
               //simulate loong running proceess
               for (int i = 0; i < 10000; i++)
               {
               }
               Console.WriteLine("i m in Deadlock2 with lock on _lock2 i need acces to _lock1");
               lock (_lock1)
               {
                   Console.WriteLine("i got _lock1");
               }
           }
       }

   }

static void Main(string[] args)
        {
            Deadlock _deadLock = new Deadlock();
            Thread thread1 = new Thread(_deadLock.Deadlock1);
            Thread thread2 = new Thread(_deadLock.Deadlock2);
            thread1.Start();
            thread2.Start();
        }

Mutex

Mutex works exactly like lock does but the major difference is that it works across process , you will want to consider mutex for thread synchronization option when working with multiple instance of the application. 

If you have a multiple instance of your application running and if your application writes to a file , then ideally you would want to write to file from one application at a time .Mutex is ideal for this kind of scenario .
class MutexTest
    {


        public static void SimulateFileWrite() 
        {
            Mutex mutex = new Mutex(true, "http://sanathwindowsdev.blogspot.in/");

            if (!mutex.WaitOne(3000))
         {
                Console.WriteLine("Other instance has the lock");
                            
         }
            else if (mutex.WaitOne())
            {
                Console.WriteLine("simulating writing to a file");
                Thread.Sleep(10000);
                mutex.ReleaseMutex();
                Console.WriteLine("simulating writing to a file done");
                
                Console.ReadKey();
            }
           
        }
        
        static void Main(string[] args)
        {
            SimulateFileWrite();
        }
          
   }
build the above code and run the exe twice,you can notice that only one app simulates the write to file at a time.

Semaphore

Semaphore is similar to mutex , but the Semaphore is not an exclusive lock , it controls  the number of thread that is allowed to enter the critical section of the code .
class SemaphoreTest
    {

      static  Semaphore semaphore = new Semaphore(3,3);
        public static void CriticalSection(object threadID) 
        {
            Console.WriteLine(threadID + "is Entering");
            semaphore.WaitOne();
            Console.WriteLine(threadID + " Entered");
            Thread.Sleep(2000 * (int)threadID);
            Console.WriteLine(threadID + " Leaving");
            semaphore.Release();
        }
        
        static void Main(string[] args)
        {
            for (int i = 1; i < 6; i++)
            {
                new Thread(CriticalSection).Start(i);
            }
            Thread.Sleep(20000);
            Console.ReadKey();
        }          
   }
When you run the above code all the time you can see that only three threads has access to critical section of the code.

We discussed about thread synchronization by locking , in the next article we will discuss about thread synchronization using signaling.