How to handle async Start () errors in TopShelf

I have a TopShelf service that uses asynchronous code to connect to web services and other application servers.

If it cannot initialize its connections at startup, the service should log some errors and stop gracefully.

I addressed this issue of stopping TopShelf when the startup conditions are not met. This answer talks about using TopShelf HostControl to stop the service.

However, this answer depends on the method ServiceConfigurator<T>.WhenStarted<T>(Func<T, HostControl, bool> start).

I am currently setting up the TopShelf service in a standard way:

x.Service<MyService>(s =>
{
    s.ConstructUsing(() => new MyService());
    s.WhenStarted(s => s.Start());
    s.WhenStopped(s => s.Stop());
});

However, my service method Start()is actually asyncdefined as follows:

public async void Start()
{
    await Init();
    while (!_canceller.Token.IsCancellationRequested)
    {
        await Poll();
    }
}

, . . , Start(), HostControl a bool, Task<bool> async.

Start(), TopShelf , . , , , . .

, :

  • async void Start() TopShelf?
  • , , Init() , , , , async?
+4
1

-, async void , "--". async Task.

.Wait() . , , async Start() StartAsync() Start(), :

public void Start()
{
    StartAsync().Wait();
}

public async Task StartAsync()
{
    await Init();
    while (!_canceller.Token.IsCancellationRequested)
    {
        await Poll();
    }
}

, TopShelf Start() "Run"(); .. , , , . , async-wait, , , Wait() Start(), Task, StartAsync(), , Stop(), Task _canceller Stop() .Wait(), - :

private Task _serviceTask;

public void Start()
{
    Init().Wait();
    _serviceTask = ExecuteAsync();
}

public void Stop()
{
    _canceller.Cancel();
    _serviceTask.Wait();
}

public async Task ExecuteAsync()
{
    while (!_canceller.Token.IsCancellationRequested)
    {
        await Poll();
    }
}

, , , , , , , async Start() TopShelf, await . Stop() _canceller.Cancel(), async Start() , Poll().

, , Poll() , . , .

Edit Init() Start(), .

+5

Source: https://habr.com/ru/post/1655590/


All Articles