How to dispose SmppServer correctly?

97 Views Asked by At

I use Inetlab.SMPP Library to implement a RE (Routing Entity in SMPP 5.0 terms). I have some questions about Stop() and Dispose() methods of an SmppServer instance:

  1. Is it necessary to call the Stop() method before disposing SmppServer instance?
  2. Does the Stop() method throw an exception if SmppServer instance is already stopped?
  3. May the methods throw an exception?

So, is the following snippet correct?

class MyService : IHostedService, IDisposable
{
    private readonly SmppServer _server = null;

    public MyService()
    {
        _server = new SmppServer()
        {
            // configure SMPP server here
        };
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _server.Start(cancellationToken);
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _server.Stop();
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _server?.Stop();
        _server?.Dispose();
    }

    // implement logic here
}

Do I need to use try...catch block within the Dispose() method? Is it possible to exclude _server?.Stop() line?

1

There are 1 best solutions below

0
Aleksey On BEST ANSWER
  1. Is it necessary to call the Stop() method before disposing SmppServer instance?

No, you don't need to call Stop method before Dispose. Dispose method as well as Stop method closes all active connections and stops the SmppServer.

  1. Does the Stop() method throw an exception if SmppServer instance is already stopped?

Stop method does nothing when SmppServer is already stopped.

I would change the snippet to


class MyService : IHostedService, IDisposable
{
    private readonly SmppServer _server;

    public MyService()
    {
        _server = new SmppServer()
        {
            // configure SMPP server here
        };
    }

   public Task StartAsync(CancellationToken cancellationToken)
    {
        return _server.StartAsync(cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return _server.StopAsync(cancellationToken);
    }

    public void Dispose()
    {
        _server.Dispose();
    }

    // implement logic here
}