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. 

Tuesday, December 30, 2014

Launching Third party Maps from your App


There could be Scenarios where you don’t really want the full control over how maps behave and want the experts (Bing maps, Nokia Maps and many more) to handle it for your , in that case all you have to do is use is

Windows.System.Launcher.LaunchUriAsync(uri) .
Now lets get into details on how to work with each of the major Map apps.

Working with Bing Maps

The Uri Schema to launch the Bing maps is "bingmaps:" and below is the simple code to launch the bing map .

private void LaunchBingMaps()
{

// The URI to launch
string uriToLaunch = @"bingmaps:?cp=140.726966~174.006076";
var uri = new Uri(uriToLaunch);
Windows.System.Launcher.LaunchUriAsync(uri);
}
**other supported parameters are bb(bounding box),lvl(zoom level),where,Q(query term),trfc(traffic),rtp(Route).

Launching Other Map apps

If you want to launch any other map apps other than bing maps then


  •  ms-drive-to :Launches the third party map apps like nokia maps , att maps in the driving Route mode
  • ms-walk-to :Launches the third party in the walking Route mode

The paramters that you pass to the URI schema are destination.latitude , destination.longitude or destination.name .

sample code snippet to launch the third party map application .

public void LaunchDrive()
{
// The URI to launch
string uriToLaunch = @"ms-drive-to:?destination.latitude=12.8399390"
+ "&destination.longitude=77.6770030&destination.name=Electonic city";
var uri = new Uri(uriToLaunch);
Windows.System.Launcher.LaunchUriAsync(uri);
}
**if there is no apps install on your phone to handle this URI schema them the user will be taken to the stores to search for the apps that handles this uri schema **if there are more than one app installed to handle this URI schema then there will be pop up dailog presented to the user to choose the app which needs to handle the schema .

Working with Map control windows phone 8.1


The fist task in hand if you want to use map controls or any other map services(drive service , walk service and more ) in your app is to authenticate your app  to use the map services and this needs to be done in the windows phone developer dashboard .

Here is the Link which will guide you to Authenticate your app to work with maps .

Once done with the above step you will get your  Map service ApplicationID and Map service AuthenticationToken .

The Maps controls for windows phone 8.1 WINRT application resides in the Windows.UI.Xaml.Controls.Maps namespace.

below is the simple code snippet to add map control to the page.

<grid background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<grid margin="12,0,12,0">
<grid .rowdefinitions="">
<rowdefinition height="Auto">
<rowdefinition height="*">
</rowdefinition></rowdefinition></grid>
<textblock fontsize="30" grid.row="0" margin="0,12,0,12" text="My Maps" textwrapping="Wrap">
<maps:mapcontrol grid.row="1" mapservicetoken="Your Map service AuthenticationToken" maptapped="MyMap_MapTapped" x:name="MyMap">
</maps:mapcontrol></textblock></grid>
</grid>
** you need to use the Map service AuthenticationToken for the MapServiceToken property of the maps control .

There are many properties available on the Maps control which allows the developer to customize the behavior and also the look and feel of the maps when it renders ,

we will see how to work with some of the most commonly used properties .

we will see how to work with some of the most commonly used properties .

Set/Get the location in the map 

use the Center property of the maps to Set/Get the location in the map , the Center Property is of the type Geopoint .

MyMap.Center = new Geopoint(new BasicGeoposition() { Latitude = 100.604, Longitude = -12.329 });

** you can also use Databind to directly bind the value to the XAML control

Set/Get the Zoom Level in the map

you can Set/Get the zoom level of your map control with the ZoomLevel Property .

MyMap.ZoomLevel = 12;
** valid values are between 1 to 20.

Set/Get the Directional Heading of the map

You can Set/Get the Directional heading of the map control with the Heading Property .

MyMap.Heading = 360;
** valid values are North =360 or 0,East =90 ,South =180,West =270 .

Set/Get the Tilt of the map

You can use the DesiredPitch Property to check if your map is tilted an angle or you can also tile you map to a desired angle by setting a valid value to this property .

MyMap.DesiredPitch = 360;

** valid values are 0 to 65.

Update a new location in the map control

if you want to update the map with a new location you should use the MapControl.TrySetViewAsync method as shown below

await MyMap.TrySetViewAsync(new Geopoint(new BasicGeoposition { Latitude = 50, Longitude = -5.399780 }));

**the method has three over loads using which you can set other parameters of the Map control like zoomlevel,heading,pitch and map animation kind when the new location value is set for the map.

Thursday, December 18, 2014

Check your Network Connectivity WindowsPhone 8

In the nutshell you all you have to do is check the NetworkInterface.NetworkInterfaceType property which is a enum with values (none,MobileBroadBandCdma,MobileBroadBandGsm,Ethernet,Wireless80211) .

bool IsConnected = NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;

you can subscribe to the NetworkChange.NetworkAddressChanged event to the Monitor the connection changes .

as simple as it looks there are a couple of gotcha's that you might want to take care of

  1. you  will want to  move the code block to monitor the network connection to a background thread a it might block the UI thread when checking  for the connection status .
  2. if the phone switches  the connection several times the NetworkAddressChanged is raised many times and it can again be issue if you are performing some time consuming task ,The Microsoft's Reactive Extension(Rx) comes in handy here , its a great framework with lot of goodies , in this case it lets to control the minimum interval  time before the NetworkAddressChanged, have used the Rx when implementing the search Contract in windows store apps where as a developer you  want to react to input typed into the search box in a timely manner (Link to Rx).
Below is the code Snippet which will check the current connection status and raises events when the connection status .
public class NetworkConnectionMonitor 
 {
  const int sampleRateMs = 1000;
  IDisposable subscription;

  public event EventHandler NetworkConnectionChanged;
  public NetworkConnectionType NetworkConnectionType  { get; private set; }

  public bool Connected
  {
   get
   {
    return NetworkConnectionType != NetworkConnectionType.None;
    //return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
   }
  }

  public NetworkConnectionMonitor()
  {
   Update();

   var observable 
    = Observable.FromEvent(
     handler => new NetworkAddressChangedEventHandler(handler),
     handler => NetworkChange.NetworkAddressChanged += handler,
     handler => NetworkChange.NetworkAddressChanged -= handler);

   IObservable> sampler 
    = observable.Sample(TimeSpan.FromMilliseconds(sampleRateMs));

   subscription = sampler.ObserveOn(Scheduler.ThreadPool).Subscribe(
                args => Update());
  }
  
  void Update()
  {
   switch (NetworkInterface.NetworkInterfaceType)
   {
    case NetworkInterfaceType.None:
     NetworkConnectionType = NetworkConnectionType.None;
     break;
    case NetworkInterfaceType.MobileBroadbandCdma:
    case NetworkInterfaceType.MobileBroadbandGsm:
     NetworkConnectionType = NetworkConnectionType.MobileBroadband;
     break;
    case NetworkInterfaceType.Ethernet:
    case NetworkInterfaceType.Wireless80211:
    default:
     NetworkConnectionType = NetworkConnectionType.Lan;
     break;
   }

   Deployment.Current.Dispatcher.BeginInvoke(new Action(
    () => NetworkConnectionChanged.Raise(this, EventArgs.Empty)));
  }
 }
** Along with the above you might want to consdier one more important paramter when downloading/uploading content  from you app, that is the datacost when the user is connected to the mobile network , The DataSense API  allows you to query if the data connection in roaming ,is the user reaching the data plan limit / exceeded the limit, based on the result the app can decided if it can download the data or not .

ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile(); \
ConnectionCost = connectionProfile.GetConnectionCost(); 
if (connectionProfile.NetworkAdapter.IanaInterfaceType = = (int) IanaInterfaceTypes.Wifi 
| | connectionCost.NetworkCostType = = NetworkCostType.Unrestricted)
{
// no need to restrict data Transfer
}
if (connectionCost.Roaming | | connectionCost.OverDataLimit)
 { // Dont tranfer any data } 
 
 if (connectionCost.ApproachingDataLimit)
 { // may be you want to warn user }

Friday, November 28, 2014

Async and Await in c# 5.0

What is Async and Await and why do we need it?

In .NET Framework 4.0 the Task Type was introduced which greatly simplified the asynchronous programming check out my article on Tasks here.  
With .NET Framework 4.5 comes C#  5.0 and brings along Async and Await which makes its writing asynchronous programs same a writing synchronous codes,will discuss more on that .

We all know when a method is called , the control only returns to the caller once the method is executed , this behavior is called synchronous .

Check out the below code    
    private  void Button_Click(object sender, RoutedEventArgs e)
        {
            Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
            Result.Text += Environment.NewLine;
            SimulateLongProcess();

           Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
           Result.Text += Environment.NewLine;
        }


       void SimulateLongProcess() 
        {         

             Longrunningtask();
       }    
       /// 
       /// Simulating Long Running Task
       /// 
       /// 
        void Longrunningtask()
        {
          
                for (int i = 0; i < int.MaxValue; i++)
                {

                }
           
       }
The Above code will freeze your UI as heavy computing is done on the main thread, you can either spin of a thread on every click of the button, or use tasks (better suited to the scenario) ,

Updated the above code to use task 
     private  void Button_Click(object sender, RoutedEventArgs e)
        {
            Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
            Result.Text += Environment.NewLine;
            SimulateLongProcess();

        }


       void SimulateLongProcess() 
        {         

             Longrunningtask();
       }    
       /// 
       /// Simulating Long Running Task
       /// 
       /// 
        void Longrunningtask()
        {

            Task.Run(() =>
            {
                for (int i = 0; i < int.MaxValue; i++)
                {

                }

                Dispatcher.BeginInvoke((Action)(() =>
                {
                    Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
                    Result.Text += Environment.NewLine;

                }

                    ));
            });
           
       }
    }
        
Task does solve the problem of freezing the UI as the heavy computing is thread pooled and then returned back to the main thread after completion of the task , if you compare the code of the synchronous execution and asynchronous exception, there is a quite a bit if difference , The Async and Await make the asynchronous  Code look more like Synchronous code

Check the Code update to use async await below:
  private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
            Result.Text += Environment.NewLine;
           await SimulateLongProcessAsync();

           Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
           Result.Text += Environment.NewLine;
        }


       async Task SimulateLongProcessAsync() 
        {         

            await LongrunningtaskAsync();
       }    
       /// 
       /// Simulating Long Running Task
       /// 
       /// 
        async  Task LongrunningtaskAsync()
        {
          await  Task.Run(() =>
            {
                for (int i = 0; i < int.MaxValue; i++)
                {

                }
            });
       }
There is a lot of patterns build around the use of async and await which is explained very well by Lucian in his Blog and Here.