Can we use Singletons? Getting a Dispatcher error if I try and use a class as a Singleton

Hi all,

I am using Glide with gadgeteer and want to make use of the PressEvent/TapEvent/ReleaseEvent events on buttons but these events are static and so I can’t reference the objects I want to modify when buttons are pressed.

Therefore I turned this object’s class into a singleton which works fine when it is referenced in the static PressEvent etc. events but if I try and use it anywhere else it doesn’t work.

For example Class A is the singleton, if I do this in Class B:

ClassA classAObject = ClassA.Instance;

and the public property instance is defined as:

private static RepWorld instance;

        public static RepWorld Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new RepWorld();
                }
                return instance;
            }
        }

then I get the runtime error:

[quote]An unhandled exception of type ‘System.Exception’ occurred in Gadgeteer.dll

Additional information: Program must be instantiated on main (Dispatcher) thread.[/quote]

and the error in the console is:

Using mainboard GHIElectronics-FEZSpider version 1.0
    #### Exception System.Exception - 0x00000000 (1) ####
    #### Message: Program must be instantiated on main (Dispatcher) thread.
    #### Gadgeteer.Program::.ctor [IP: 0025] ####
    #### test.Program::.ctor [IP: 0004] ####
    #### test.Program::Main [IP: 000b] ####
A first chance exception of type 'System.Exception' occurred in Gadgeteer.dll
An unhandled exception of type 'System.Exception' occurred in Gadgeteer.dll

If I take out this

ClassA classAObject = ClassA.Instance;

and just make

classAObject = null;

for now then the error goes away.

Has anyone else hit this problem with singletons?

Or does anyone know another way around the PressEvent/TapEvent/ReleaseEvent static event problem with referencing objects?

Thanks for your time,

Poncho

Can you please show your actual code?

Please take a look at this project as well:

http://www.tinyclr.com/codeshare/entry/349

Good example on how to use Glide with Gadgeteer.

Ah so the PressEvent/TapEvent etc. don’t have to be static? I just assumed they did because when you auto-complete the event handler it makes them static, now that they don’t have to be static it works fine.

Thanks for the help yet again Architech :slight_smile:

You are welcome!