Hello guys,
As you all know Gadgeteer runs a main dispatcher where all theMOdules are created. so if you try to add and initilize a Module outside of the main dispatcher, for example inside a new Thread you will get an exception "Modules must be added to the Main Dispatcher " so i followed the exception found in the Module.cs Gadgeteer core source… which looks like this:
// Note: A constructor summary is auto-generated by the doc builder.
/// <summary></summary>
protected Module()
{
if (!Program.Dispatcher.CheckAccess()) throw new Exception("Modules must be created on the Program's Dispatcher thread");
DebugPrintEnabled = false;
Module.modules.Add(this);
}
So i was wondering could one use the following code instead.
// Note: A constructor summary is auto-generated by the doc builder.
/// <summary></summary>
protected Module()
{
// if (!Program.Dispatcher.CheckAccess()) throw new Exception("Modules must be created on the Program's Dispatcher thread");
if (Program.Dispatcher.CheckAccess())
{
DebugPrintEnabled = false;
Module.modules.Add(this);
}else
{
Program.Dispatcher.Invoke(new TimeSpan(100), myDispCallBack, Module.modules);
}
}
private object myDispCallBack(object arg)
{
// throw new NotImplementedException();
(Module.modules).Add(this);
return null;
}
The above code will run the check and if it fails instead of an Exception error it will get dispatched and run from inside the main dispatch … i tried it and it works… but i’m not sure why it was done this way in the first place… or this will lead to some catastrophic failures down the road?
Here is a sample code that throws the exception before the fix and not after:
//create a new Gadgeteer Project add the spider and the DP Module and that's it no other modules should be added..
//next right click on References and add choose "GTM.GHIElectronics.Button"
//next paste the code below and replace your void ProgramStated() run it and it should throw the exception now open the Module.cs from the Gadgeteer Source code (get it from gadgeteer.codeplex.com), modify the module.cs according to the change above. rebuild the project. now go back to references and delete Gadgeteer from there and right click on References and choose add, click on Browse and choose the Gadgeteer source code folder nad pick the Gadgeteer dll that you've just built.. rebuild your project and run .. now it won't throw the exception and your button press will work as they should.
// This method is run when the mainboard is powered up or reset.
void ProgramStarted()
{
Thread myThread = new Thread(MyThreadMethod);
myThread.Start();
}
private void MyThreadMethod()
{
Gadgeteer.Modules.GHIElectronics.Button button;
button = new Gadgeteer.Modules.GHIElectronics.Button(11);
//please add a button module using gadgeteer designer.
button.ButtonPressed += new Button.ButtonEventHandler(button_ButtonPressed);
}
please let me know your thoughts.
Thanks.
Jay.