Skip to content

Using events

Alexey Yakovlev edited this page May 21, 2018 · 1 revision

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.

Luckily, 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 argument types should be serializable so they can be transferred across the wire.
  • Events provided by server components should be defined in the interface known both to the client and the server.
  • If server fails to invoke client's event handler, subscription is cancelled, and client's event handler is removed.
  • Event handlers are invoked sequentially, just like in local scenarios. If many clients are subscribed to server's event, invoking event handlers can be slow.
  • Network access is always much slower than direct memory access. Distributed events are much slower than local events.
  • Events don't work in multi-server clusters. Client subscribed to server X's event should not expect that server Y will fire the event if server X goes offline.

Event subscriptions work with any ProtocolSetup.

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