I wish to create own events and dispatch them. I never done this before in C#, only in Flex.. I guess there must be a lot of differencies.
Can anyone provide me a good example?
I wish to create own events and dispatch them. I never done this before in C#, only in Flex.. I guess there must be a lot of differencies.
Can anyone provide me a good example?
Look into 'delegates'.
Hope this helps,
Events in C# use delegates.
public static event EventHandler<EventArgs> myEvent;
static void Main()
{
//add method to be called
myEvent += Handler;
//call all methods that have been added to the event
myEvent(this, EventArgs.Empty);
}
static void Handler(object sender, EventArgs args)
{
Console.WriteLine("Event Handled!");
}
There is a pattern. Here is an example based on the simplest event-delegate,
// the delegate type, from the library, in the System namespace
public void Eventhandler(object sender, Eventargs args);
// your class
class Foo
{
public event EventHandler Changed; // the event
protected virtual void OnChanged()
{
EventHandler handler = Changed; // make a copy to be more thread-safe
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
And how to use it:
class Bar
{
void OnFooChanged(obkect sender, EventArgs args) // handle (react)
{
//
}
void Setup()
{
Foo f = ....
f.Changed += OnFooChanged; // subscribe
}
}
Using the typical .NET event pattern, and assuming you don't need any special arguments in your event. Your typical event and dispatch pattern looks like this.
public class MyClassWithEvents
{
public event EventHandler MyEvent;
protected void OnMyEvent(object sender, EventArgs eventArgs)
{
if (MyEvent != null)
{
MyEvent(sender, eventArgs);
}
}
public void TriggerMyEvent()
{
OnMyEvent(sender, eventArgs);
}
}
Tying something into the event can be as simple as:
public class Program
{
public static void Main(string[] args)
{
MyClassWithEvents obj = new MyClassWithEvents();
obj.MyEvent += obj_myEvent;
}
private static void obj_myEvent(object sender, EventArgs e)
{
//Code called when my event is dispatched.
}
}
Take a look at the links on this MSDN page