0

I have a Windows Mobile 6.5 (.net cf 3.5) that uses a singleton class which follows this pattern:

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

reference

My class used to collect GPS data from the Intermediate drive. What I want is to create an event on the singleton class that I can subscribe to? E.g. MyClass.Instance.LocationChanged += ...;

Any help would be greatly appreciated.

Mark

Community
  • 1
  • 1
markpirvine
  • 1,485
  • 1
  • 23
  • 54
  • Be careful, any code that subscribes the event has to *explicitly* unsubscribe it. Failing to do so causes a memory leak. – Hans Passant Dec 16 '10 at 15:06

2 Answers2

3

What's the problem?

public sealed class Singleton
{
  ... your code ...

  public delegate LocationChangedEventHandler(object sender, LocationChangedEventArgs ea);  

  public event LocationChangedEventHandler LocationChanged;

  private void OnLocationChanged(/* args */)
  {
    if (LocationChanged != null)
      LocationChanged(this, new LocationChangedEventArgs(/* args */);
  }
}

public class LocationChangedEventArgs : EventArgs
{
  // TODO: implement
}

Call OnLocationChanged whenever you want to fire the event.

VVS
  • 19,405
  • 5
  • 46
  • 65
0

You should just be able to do this as you would an event on any class.

public event Action<object, EventArgs> LocationChanged;

you can then have a protected virtual method such as:

protected virtual void OnLocationChanged(EventArgs args)
{
   if(LocationChanged != null)
   {
     LocationChanged(this, args);
   }
}

You can fire off your OnLocationChanged method where ever you need too and the event's you've attached will do their thing.

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162