Skip to content

Channel Services

Sometimes you may need to execute a long-running task within a channel, or run logic when a channel is created. For example, you might want to periodically send a message to the channel, or send a message to the channel when a new client connects.

The easiest way to create such mechanism, is to use a Channel Service. These are lightweight services whose 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.

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 handles task initialization, so you only need to implement the worker method. However, if you have different requirements, you can also implement the IChannelService interface directly. This can be useful if you only need to execute logic when the channel is created or closed, without the need for a long-running task.

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>();