Using events

An event is an action that is initiated somewhere outside of your code and is handled inside your code. User interface is a typical example of event-driven environment where events (such as keystrokes or mouse clicks) are initiated by end-user and handled by your application. For example, to handle button's Click event you should subscribe to it:

button1.Click += button1_Click;

...

private void button1_Click(object sender, EventArgs args)
{
    MessageBox.Show("The button has been clicked.");
}

Nothing new so far. But how should we handle events raised by the component instantiated on the remote computer?

In .NET Framework we have two options for building distributed applications: WCF and .NET Remoting. Both of them don't provide straightforward support for event model similar to that shown in the example above. To get similar functionality in WCF, we should implement Duplex Contract. Handling events in .NET Remoting requires weird stuff such as referencing client's metadata from server (to work around this, we should implement middle-tier event repeater referenced by both client and server). Too much clumsy hand work compared to button1_Click simplicity shown above.

Luckyly, Zyan provides distributed event handling in button1_Click-style out-of-the-box. The following code works with Zyan with no problems:

chatProxy = _connection.CreateProxy<IMiniChat>();
chatProxy.MessageReceived += chatProxy_MessageReceived;

...

private void chatProxy_MessageReceived(string name, string text)
{
    MessageBox.Show(string.Format("{0} says: {1}", name, text));
}

Firing events across network is easy and straightforward, but you should be aware of the following:
Event subscriptions work with any ProtocolSetup.

Here is a simple example application which utilizes event handling: Mini-Chat Project