Skip to content

Channel Services

Sometimes it might be required to execute a long-running task inside a channel, or execute some code when a channel is created. For example, we might want to periodically send a message to the channel, or we might want to send a message to the channel when a new client connects.

The easiest and fastest way to create such mechanism, is to use a Channel Service. These are lightweight services which lifetime is bound to the channel. When a new channel is created, a service instance is created and started; when the channel closes, the service is stopped (if still running) and disposed of.

Note

Channel services are bound to channels. A new instance is created for each channel and disposed of when the channel is closed.

The recommended way to create a channel service is to inherit from the ChannelService base class and implement the ExecuteAsync method.

public class MyService : ChannelService
{
    protected override async Task ExecuteAsync( CancellationToken stoppingToken )
    {
        while ( !stoppingToken.IsCancellationRequested )
        {
            // insert code...

            /*
            here we have access to the channel instance
            this instance is never null (but can be closed)
            */

            // await Channel.WriteAsync( ... );

            await Task.Delay( 1000 );
        }
    }
}

The base class takes care of the task initialization for us, so all we have to do is to implement the worker method. However, if you have different requirements, you can also implement the IChannelService interface directly. This might be useful if, for example, you just want to execute some code when the channel is created.

public class MyService : IChannelService
{
    // ...

    public Task StartAsync( IChannel channel, CancellationToken cancellationToken )
    {
        // Invoked when a channel is created
    }

    public Task StopAsync( CancellationToken cancellationToken )
    {
        // Invoked when a channel is closed
    }

    public void Dispose()
    { }
}

To set up the service, we use the channel builder to register it.

IChannelBuilder channel = ...;

channel.AddChannelService<MyService>();