Channels
In asynchronous programming, it is important to be able to control the thread context of actions performed within a class. By having public methods that anyone with a reference to the class can call, it is impossible to ensure that all operations on the class are done in a manner that ensures thread safety. Making methods private doesn’t help either, since other classes would not be able to take advantage of the features provided by the class. Clearly, there needs to be a way to invoke methods on a class while ensuring the object remains in a valid state.
Channels provide a way for objects to call methods on another object while keeping control of the execution context in the hands of the target object. Instead of calling a method with a set of parameters, a message is sent to the class instead. Inside the target class, the message type is mapped to a method that accepts the properties of the message as arguments. In most cases, it is easiest to simply pass the message directly to the method — but this is not required. A set of channel adapters are available to handle the mapping for the class, which can be created and assigned to the public channel properties in the class constructor.
Channel
A marker interface implemented by a class that has an input channel. This is used only to discover channels on a class via reflection.
Channel<T>
A data type channel can send messages of the type specified by the generic argument T to the implementor of the channel interface. A single method, Send, is called to send a message to the object.
Adding Channels To A Class
To add a channel to a class, the best method is to add a read-only property for the channel.
public class MyClass
{
public MyClass()
{
MyMessageChannel = new ConsumerChannel<MyMessage>(HandleMyMessage);
}
public Channel<MyMessage> MyMessageChannel { get; private set; }
private void HandleMyMessage(MyMessage message)
{
// do something with the message
}
}
Once the property is added, another class can get the channel from your object and call the Send method to send messages to your object.
There are a number of channel implementations available to handle routing the messages to your class based on the needs of your class. If your class is also using the ActionQueue features, a number of default channels are available that will enqueue incoming messages to your objects ActionQueue ensuring that the message is processed within the context of your object.