Hi All,
I am working on a project that requires handling of custom events. Some class will raise the DataEvent of RaiseEventClass. I have to implement event handler for the DataEvent in the RaiseEventClass. Please help me how to implement event handler. Please show some codes if possible.
Below is the skeleton of the class.
Thanks in advance!
public class RaiseEventClass
{
public delegate void RaiseEventDelegate(ArrayList files);
public event RaiseEventDelegate DataEvent;
public void SearchFiles(ArrayList list)
{
DataEvent(list); //raising event for testing
}
}
Matthew CochranPosted Jan 25, 2008, 5:13 PM
SerialPort sp = new SerialPort();
sp.DataReceived += sp_DataReceived;
You could just re-fire your own event
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (null != myEvent)
myEvent(this, EventArgs.Empty);
}
Hope this helps
-Matt
Matthew CochranPosted Jan 25, 2008, 5:08 PM
Socket s = new Socket(AddressFamily.Unknown, SocketType.Stream, ProtocolType.Tcp);
s.BeginReceive(buffers, SocketFlags.None, x =>
{
if (null != myEvent)
myEvent(this, EventArgs.Empty);
}, null);
Of course, you'd have to modify for your application and add exception handling.
Posted Jan 25, 2008, 4:54 PM
Say I have a Socket, and I want to create an event to be raised when data is received on that socket like the SerialPort.DataReceived event. How could that be achieved?
Matthew CochranPosted Jan 25, 2008, 9:31 AM
Always make sure to make your events private to protect them and expose through the accessors as below. Also, always check the event is not null which happens if there are no subscribers and will throw an exception.
-Matt
public class EventArgs:
EventArgs
{
public EventArgs(T pValue)
{
m_value = pValue;
}
private T m_value;
public T Value
{
get { return m_value; }
}
}
{
// protect your events!
private event EventHandler<EventArgs<ArrayList>> m_DataEvent;
public event EventHandler<EventArgs<ArrayList>> DataEvent
{
add { m_DataEvent += value; }
remove { m_DataEvent -= value; }
}
public void SearchFiles(ArrayList list)
}
{
if (null != m_DataEvent) // always check if null (no subscribers)
m_DataEvent(this, new EventArgs<ArrayList>(list));
}