Search code examples
c#multithreadingcompact-frameworkgpsiasyncresult

Help me solve this Threading issue with GPS


I have a GPS class which i obviously use to acquire the latitudes and longitudes.

The UpdateData() is called when the gps state or location is changed. So i make sure that both the Latitude and Longitude is valid and then i make the DataReady bool equal to true.

So i use this code in a fairly n00b fashion where i use a Timer (Windows Form's one) and check getGPSCoordinates() every 10 seconds to see whether a valid location is found (getGPSCoordinates() is not null) and if not, do the rest of code. This is used, as it may take from 10 seconds to maybe even 1 minute to get a clear gps signal.

So although this works fine, i know this is not the correct way to do this. I think whole GPS business should be carried on a separate thread and it should notify the main thread that the location is changed and the data is ready.

Can someone point me on the correct way of handling these kinds of business? Should i use IAsyncResult to notify the main thread?

bool DataReady = false;

private void UpdateData()
        {

            if (gps.Opened)
            {
                if (position != null)
                {

                    if (position.LatitudeValid)
                    {
                        Latitude =  position.Latitude.ToString();
                    }


                    if (position.LongitudeValid)
                    {
                        Longitude = position.Longitude.ToString();

                    }

                    if (Latitude != null && Longitude != null)
                        DataReady = true;          


                }



            }


 public string getGPSCoordinates()
        {
            if (DataReady)
            {
                return String.Format("http://maps.google.com/maps/api/staticmap?sensor=false&size=500x500&markers=color:red|label:A|{0},{1}&zoom=15&maptype=hybrid", Latitude, Longitude);
            }
            else
                return null;
        }


        }

Solution

  • It sounds like you want to use a BackgroundWorker - however this isn't natively supported in the Compact Framework. Again however, this can be addressed:

    Is there a BackgroundWorker replacement for .NET Compact Framework 3.5?

    You can then call into your background worker whenever your UI timer ticks (make sure to pause your UI timer until you get a response).

    If you cannot use the implemented BackgroundWorker from that question, you will need to maintain a Queue or List that both the UI and the background can see. Using a normal thread will likely mean registering a callback (fairly standard, using your IAsyncResult idea) however this callback is run on an unknown, arbitrary thread - this makes updating your UI a little finicky.