I was used to write Gadgeteer Applications but now I have to port things to pure NETMF.
There seem to be differences how to throw events.
In a Gadgeteer Application I had to use code like this:
protected virtual void OnEventWasThrown(string pTheMessage)
{
if (onEventWasThrown == null)
{
onEventWasThrown = OnEventWasThrown;
}
if (Program.CheckAndInvoke(EventWasThrown, onEventWasThrown, pTheMessage))
{
EventWasThrown(pTheMessage);
}
}
In a NETMF application I could not manage to use the Program.CheckAndInvoke method, so I supposed that I could not access members of the main thread as I thought that they were out of the scope.
Surprisingly I can!! (see example).
However is it correct to use the events without checking the need to invoke?
How is it done correctly?
Example:
using System;
using Microsoft.SPOT;
using System.Threading;
namespace EventThrowTest_NETMF
{
public class Program
{
static EventThrower myEventThrower;
static string messageFromMainThread = "This message from the main thread was printed";
public static void Main()
{
Debug.Print(Resources.GetString(Resources.StringResources.String1));
myEventThrower = new EventThrower();
myEventThrower.EventWasThrown += myEventThrower_EventWasThrown;
myEventThrower.Start();
while (true)
{ }
}
static void myEventThrower_EventWasThrown(string pTheMessage)
{
Debug.Print(pTheMessage);
Debug.Print(messageFromMainThread);
}
}
//******************************************************
class EventThrower
{
public delegate void TheEventHandler(string theMessage);
public event TheEventHandler EventWasThrown;
private TheEventHandler onEventWasThrown;
private Thread workThread;
public EventThrower()
{
Debug.Print("Class EventThrower instantiated");
workThread = new Thread(new ThreadStart(runWorkThread));
}
void runWorkThread()
{
Debug.Print("I'm in the workThread");
OnEventWasThrown("This message from EventThrower thread was printed");
}
public void Start()
{
workThread.Start();
}
protected virtual void OnEventWasThrown(string pTheMessage)
{
if (onEventWasThrown == null)
{
onEventWasThrown = OnEventWasThrown;
}
/* this is the way to do it in a Gadgeteer application
if (Program.CheckAndInvoke(EventWasThrown, onEventWasThrown, pTheMessage))
{
EventWasThrown(pTheMessage);
}
*/
EventWasThrown(pTheMessage);
}
}
}