C# /CSharp

C# Event Factory for other projects to listening on

Unlike Java it is possible to signal events between processes by listening on Events. This events are not forced to be in the same project or in the same class.

Here I want to demonstrate that the way of sending events could be in a own undependable project, where other projects only adds as references and thereby can listening on, without any knowledge of the project that sending the events.

It should also be mention that the events triggering always is a own thread, and since more and more kernels are added to the cpu’s, threaded environment is the way to go to better use the cpu effectively, if the application should live for a long time.

Here is the main class for the events:

namespace EventFactor
{
///

/// To subscribe to the event simple use a example:
/// EventFactor.EventDispatcher.Instance.DataUpdateEvent += new EventFactor.EventDispatcher.DataUpdate(UpdateData);
///
/// To trigger an event
/// UnknownData data = null;
/// make stuff to data
/// Excecute the event
/// if (EventFactor.EventDispatcher.Instance.EventDataUpdate != null)
/// EventFactor.EventDispatcher.Instance.EventDataUpdate(data);
///

public class EventDispatcher
{
#region Delegates
public delegate void DataRefresh();
public delegate void DataUpdate(UnknownData data);

// Declaring the Events
public event DataRefresh DataRefreshEvent;
public event DataUpdate DataUpdateEvent;
#endregion

///

/// Handle this Instance as a Singelton that makes this a central point where all events are executed.
///

private static readonly EventDispatcher instance = new EventDispatcher();

///

/// Default Singleton Instance
///

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

#region Get/Set

public DataUpdate EventDataUpdate
{
get { return DataUpdateEvent; }
}

public DataRefresh EventDataRefresh
{
get { return DataRefreshEvent; }
}

#endregion
}
}

Then we have the code that should listen on the events:

Listener Class


....
EventDispatcher.Instance.DataUpdateEvent +=
new EventDispatcher.DataUpdate(dataUpdate);
....
....
private void dataUpdate(object updateData)
{
UnknownData unknownUpdateData = (UnknownData) updateData;
... do stuff to data ...
}

And finally the code that is used to trigger it.

Class that trigger the event


UnknownData dataToSend;
...
if (EventDispatcher.Instance.DataUpdate != null)
EventDispatcher.Instance.DataUpdate(dataToSend);

2 thoughts on “C# Event Factory for other projects to listening on

Leave a Reply

Your email address will not be published. Required fields are marked *